3주차 Front-E 스터디 TIL React

박규원·2023년 10월 27일
0

노드를 설치하고 server/client개념을 익혔다.

server/client 폴더를 만들고,
api 호출을 통한 서버와 클라이언트 간의 통신 개념을 처음 알게 되었다.

postman을 설치 받아 get,post 로 todolist를 받아보는 연습을 했다.

express를 통해 서버간의 통신이 이루어진다는 것을 알게 되었다.

여러가지 패키지 설치를 해야하고, 오류들이 생기는 바람에 시간이 오래걸려서 아쉬웠다.

기록을 위해 서버와 클라이언트 각각의 코드를 첨부한다.

server src/app.js

import './App.css';
import { useState, useEffect } from 'react';


function App() {
  const [ todoList, setTodoList ] = useState(null);

  useEffect(() => {
    fetch('http://localhost:8080/api/todo')
    .then((response) => response.json())
    .then((data) => setTodoList(data));
  }, []);

  const onSubmitHandler = (e) => {
    e.preventDefault();
    const text = e.target.text.value;
    const done = e.target.done.value;

    fetch('http://localhost:8080/api/todo', {
      method : 'POST',
      headers : {
        'Content-Type' : 'application/json',
      },
      body : JSON.stringify({
        text,
        done,
      }),
    }).then(
      fetch('http://localhost:8080/api/todo')
      .then((response) => response.json())
      .then((data) => setTodoList(data))

    );
  };

  return (
    <div className="App">
      <h1>TODO LIST</h1>
      <form onSubmit={onSubmitHandler}>
        <input name = 'text' />
        <input name = 'done' type='checkbox' />
        <input type = 'submit' value='추가' />
      </form>

      {todoList && todoList.map((todo) => (
         <div key={todo.id}>
          <div>{todo.id}</div>
          <div>{todo.text}</div>
          <div>{todo.done ? 'Y' : 'N' }</div>
        </div>
      ))}
    </div>
  );
}

export default App;

client/server

// const express = require('express')
// const app = express()

// app.get('/', function (req, res) {
//   res.send('Hello World')
// })

// app.listen(8080, ()=>{
//     console.log('server started!');
// });

// 


const express = require('express')
const app = express()
const port = 8080

const user = [
    {
        name: 'alex',
        age: 25,
    },
    {
        name: 'jane',
        age: 20,
    },
    {
        name: 'alex',
        age: 41,
    }
]

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})
profile
Just do IT

0개의 댓글