fetch - axios 사용 / 서버에 데이터 요청

연주·2022년 10월 31일
0

KDT-TIL

목록 보기
28/36

프론트에서 서버에 데이터 요청하는 방법

  • fetch : 리액트 기본 제공
  • axios : 다운이 필요한 라이브러리

서버 실행 - 📁 server

🧷 app.js

const express = require('express');
const app = express();
const cors = require('cors');
// cors에러 서로 다른 포트에서 무언가 요청하게 되면
// 보안상의 이유로 cors에러가 뜨게 된다.
// 미들웨어로 해결

// 익스프레스에서 바디에서 데이터를 꺼내쓰려면 body-parser가 필요함
// 바디 파싱을 하려면 아래 두 줄을 입력해야한다.
app.use(express.json()); // 파싱을 위한 어플리케이션
app.use(express.urlencoded({ extended: true })); // 파싱
app.use(cors());

let id = 2;
const todoList = [
  {
    id: 1,
    text: '할일 1',
    done: false,
  },
];

app.get('/', function (req, res) {
  res.send('Hello World');
});
// 화면에 Hello World를 띄운다.

app.get('/api/todo', (req, res) => {
  res.json(todoList);
  // json형태로 보내준다.
});

// 바디에 데이터를 담아서 보낸다.
app.post('/api/todo', (req, res) => {
  const { text, done } = req.body;
  todoList.push({
    id: id++,
    text,
    done,
  });
  return res.send('success');
});

app.listen(5000, () => {
  console.log('server start!!');
});
// 서버 실행

📁client

🧷 app.js

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

function App() {
  const [todoList, setTodoList] = useState(null);
  const fetchData = () => {
    fetch('http://localhost:5000/api/todo')
      .then((response) => response.json())
      .then((data) => setTodoList(data));
  };
  // 중복으로 쓰여지는 코드를 묶어서 썼다.
  
  useEffect(() => {
    fetchData();
  }, []);
  // 다음 응답값은 todolist 데이터 이다.
  // 리렌더링이 반복되는 걸 방지하기 위해, useEffect()를 사용

  const onSubmitHandler = (e) => {
    e.preventDefault();
    // 브라우저 고유의 동작을 중단시켜주는 역할
    // onsubmit했을때, 리프레쉬 되는 걸 막아는 준다.
    
    const text = e.target.text.value;
    const done = e.target.done.checked;
    fetch('http://localhost:5000/api/todo', {
      method: 'POST',
      headers: {
        'content-Type': 'application/json',
      },
      body: JSON.stringify({
        text,
        done,
      }),
      // json이라고 알려줘야 파싱을 해준다.
    }).then(() => {
      fetchData();
    });
  };

  return (
    <>
      <h1>TODO LIST</h1>
      <form onSubmit={onSubmitHandler}>
        <input name='text' />
        <input name='done' type='checkbox'></input>
        <input type='submit' value='추가' />
      </form>
      {todoList?.map((todo) => (
        <div key={todo.id} style={{ display: 'flex' }}>
          <div>{todo.id}</div>
          <div>{todo.text}</div>
          <div>{todo.done ? 'Y' : 'N'}</div>
        </div>
      ))}
    </>
  );
}

export default App;

// server에서 응답이 오면 코드를 실행시킨다.
// react는 상태를 바꾸면 리렌더링이 일어난다.
// fetch를 만나면 서버에 요청을 보낸다, 서버에 응답이 오면 setTodoList 상태 변화
// 리렌더링이 반복해서 나타난다.
// 계속 리렌더링 되는이유는 fetch가 그렇게 작성되어있기때문

// 처음 컴포넌트 렌더링 될때만 실행됬으면 좋겠다 -> useEffect

axios 사용

fetch라고 쓰여있는 자리에 axios를 입력 후 json 부분도 지운다.
fetch는 json데이터 포맷이 아니기 때문에, json형태로 만들어 줬지만,
-기본적으로 json타입으로 사용할 수 있다.
-자동 문자열 반환도 된다.
-에러처리가 간결하다.

const fetchData = () => {
axios.get('http://localhost:5000/api/todo')
      .then((data) => setTodoList(data));
  };

async await 사용

 const fetchData = async () => {
  const response  = await axios.get('http://localhost:5000/api/todo')
      setTodoList(response.data);
  };

fetch -> axios 사용

  const onSubmitHandler = async (e) => {
    e.preventDefault();
    const text = e.target.text.value;
    const done = e.target.done.checked;
    await axios.post(SERVER_URL, { text, done });
    fetchData();
    
    // fetch('http://localhost:5000/api/todo', {
    //   method: 'POST',
    //   headers: {
    //     'content-Type': 'application/json',
    //   },
    //   body: JSON.stringify({
    //     text,
    //     done,
    //   }),
    // json이라고 알려줘야 파싱을 해준다.
    // }).then(() => {
    //   fetchData();
    // });
  };

직렬화 해줬던 부분, 헤더에 컨텐트 타입 넣어줬던 것,
method 넣었던것들을 넣지 않아도 , 간단하게 쓸 수 있어서 코드가 깔끔해진다.

profile
성장중인 개발자🫰

0개의 댓글