0

I am making simple code getting input from frontend(react) and sending it to backend(nodejs).

But it does not work well in backend with req.body .

I made input's name "place" and send using method of post.

If I print req.body, just empty string is printed with type of object.

I tried to find solutions using body-parser and cors but nothing changed.

Here is my nodejs code and part of react code !! Could you tell me where to fix? thank you

const express = require('express') ;
const app = express(); 
var bodyParser = require('body-parser'); 
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const cors= require('cors') ;
app.use(cors()) ; 
const placeList = [
    {
        text: '연수', 
    }, 
]; 


app.get('/', function(req,res){
    res.send('hello world'); 
});
app.get('/api/', (req, res )=>{
   //리스트를 읽어서 보여주는 경우 response로 동작시키기
    res.json(placeList) ; 
}) ; 

app.post('/api/', (req,res)=>{
    //백엔드에서 프론트의 정보를 받는 경우 request로 동작시키기 
    const place =req.body ;
    const newplace =place.place; 
    console.log(typeof(place)) ; //object
    console.log(req.body) ;      //{}
    console.log(place) ;         //{}   
    console.log(newplace) ;      //undefined
    console.log(place.place) ;   //undefined
    return res.send(`success `)
}); 

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

React code

function App() {
  const[placelist , setPlaceList ]= useState(null) ; 
  useEffect(()=>{
    //useeffect로 언제 데이터 불러올 지 결정하기
    fetch('http://localhost:8080/api')
    .then((response)=>response.json())
    .then((data)=>setPlaceList(data)); 
  }, []) ; 
  
  const onSubmitHandler =(e)=>{
    e.preventDefault(); 
    const place =e.target.place.value ; 
    console.log(place) ; 
    console.log(typeof(place)) ; 
     
    fetch('http://localhost:8080/api/',{
      method:'POST' ,
      body: JSON.stringify({
         place}),
    });
    
  }; 
    return (  
    <div className="App">
      <h1>hi</h1>
      <form onSubmit={onSubmitHandler}>
        <input name='place'/>
        <input type='submit' value ='추가'/>
      </form>
      {placelist?.map((place)=>(
        <div key = {place}>
          <div>{place.text}</div>
          
        </div>
      ))}
    </div>
  );
}
smrmaak
  • 11
  • 2

2 Answers2

0

Check your express version, if it <4.12 - you need use bodyParser, if > 4.12 use express.json() and add headers: { 'Content-Type': 'application/json' }, to your fetch

as_yokai
  • 1
  • 2
-1

When passing data to the API it should be in the object form like

JSON.stringify({"place": place});

Because on the server side, the data is parsed as the JSON object, so the passed data must be a JSON object.

  • `JSON.stringify({ place })` and `JSON.stringify({"place": place})` are exactly the same – Phil Dec 29 '22 at 04:01