프론트엔드 3번째 TIL

김윤경·2023년 10월 10일
0

FrontEnd

목록 보기
10/12
post-thumbnail

📅2023.10.10

💡 React

CRUD

=> Create Read Update Delete

express 서버 생성

  • client와 server 파일 생성
  • server 파일에서 yarn init
  • npm install express
  • app.js 파일 생성 (아래 코드 작성)
  • 터미널에서 node app.js 실행
const express = require('express')
const app = express()

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

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

postman

const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json());

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

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

app.get('/api/todo', (req, res) => {
  res.json(todoList);
})

app.post('/api/todo', (req, res) => {
  const { text, done } = req.body;
  todoList.push({
    id: id++,
    text,
    done,
  });
  return res.send('success');
});

app.listen(8080, () => {
  console.log('server started!');
});
  • 구글에서 postman 검색 후 설치
  • 8080번 포트에 값이 오는지 확인
  • 8080/api/todo 의 값이 오는지 확인
  • post 상태에서 body에 아래 코드 작성
{
    "text": "todo 2",
    "done": true
}
  • client 파일로 들어가기
  • yarn create react-app 폴더이름
  • App.js에 아래 코드 작성
import './App.css';
import { useState } from 'react';


function App() {

  return (
    <div className="App">
    	<h1>TODO LIST</h1>
    </div>
  );
  
}

export default App;

-> fetch만 사용하면 런타임 에러 발생 !!!

  • useEffect를 사용해서 렌더링될 때만 불려오게 만들기
import './App.css';
import { useEffect, useState } from 'react';


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

  useEffect(() => {
    // 자바스크립트에 내장된 api를 사용할 수 있는 함수
    fetch('http://localhost:8080/api/todo')
      .then((response) => response.json())
      .then((data) => setTodoList(data));
  }, []);

  return (
    <div className="App">
    	<h1>TODO LIST</h1>
    </div>
  );
}

export default App;

0개의 댓글