简体   繁体   中英

Axios post request body is just an empty object on the server side (React - Axios - Node.js - Express)

I was trying to send a post request to my server and was using this:

let dataToReturn = {
      method: "POST",
      url: "http://localhost:9000/logData",
      headers: { "testing" : "IT WORKED" },
      body: {"hola" : 'testing to see if this counts'}
    }

axios(dataToReturn) 

It know it would send. I checked the network tab in inspector and could see that it was sent, and could do req.headers on the server and it would print out the headers. But whenever I tried to log req.body on the server it would just print out '{}'

  var body = {
      firstName: 'testName',
      lastName: 'testLastName'
  };

  axios.post('http://localhost:9000/logData', body)
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

This works tho ^^ and successfully prints out the body when I do 'req.body' Why does the top example log an empty object?

Here's what the route looked like on the server side

app.post('/logData', function(req, res) {
    console.log('recieved post');
    console.log(req.body);
    res.sendStatus(200);
})

I acknowledge that I'm a noob and this might be a dumb question, so please excuse my ignorance. Also happy to post more info if you need it.

You need to add content type in the header of your request.change your header as mentioned below

headers: { "testing" : "IT WORKED","Content-Type":"application/json" },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM