• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 리액트에서 axios post 요청

리액트에서 axios post 요청

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #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')
    })
     
     
    #52459

    codingapple
    키 마스터
    submit 버튼누르면 새로고침되어서 그런듯요 새로고침되지 않게 해봅시다
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠