2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2022년 11월 2일 21:18 #52405

현정참가자node.js 에서 데이터를 보낸뒤 리액트에서 post 했을때 데이터를 추가하고 싶은데 안되네요 콘솔창에 아무것도 안떠서 뭐가 에러인지도 확인이 안돼서 어떻게 해야되는지 모르겠어요ㅠㅠ axios get 요청은 정상적으로 되는데 왜 post는 안될까요 input 에 입력하면 url이 http://localhost:3000/?text=%ED%95%A0%EC%9D%BC2&done=on 이런식으로만 뜨고 추가되지가 않네요 (리액트)
<App.js>
import axios from 'axios'; import { useState,useEffect} from 'react' const SERVER_URL = 'http://localhost:5000/api/todo' function App() {const [todoList,setTodoList] = useState([])
const fetchData = async () => { const res = await axios.get(SERVER_URL) setTodoList(res.data) }useEffect(()=>{ fetchData() },[])const onSubmitHandler = async (e) => { e.preventDefalut(); const text = e.target.text.value; const done = e.target.done.checked; await axios.post('http://localhost:5000/api/todo',{text,done}) fetchData(); }return ( <div className="App"> <h1>TODO LIST</h1>
<form onSubmit={onSubmitHandler}> <input name='text'/> <input name='done' type='checkbox'/> <input type='submit' value='add'/> </form>{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; (노드) <app.js>
const express = require('express'); const cors = require('cors'); const app = express();app.use(cors()); app.use(express.json()); app.use(express.urlencoded({extended:true}))app.get('/', function(req,res){ res.send('hi') })app.listen(5000,()=> { console.log('server start'); })let id = 2; const todoList = [ { id:1, text:'할일1', done:false, } ]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') }) -
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.
