简体   繁体   English

Axios post 请求体只是服务器端的一个空对象(React - Axios - Node.js - Express)

[英]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:我试图向我的服务器发送一个 post 请求并使用这个:

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.我检查了检查器中的网络选项卡,可以看到它已发送,并且可以在服务器上执行 req.headers 并打印出标题。 But whenever I tried to log req.body on the server it would just print out '{}'但是每当我尝试在服务器上记录 req.body 时,它只会打印出“{}”

  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?这行得通 ^^ 并在我执行 'req.body' 时成功打印出正文 为什么最上面的示例记录了一个空对象?

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" },标头:{“测试”:“它有效”,“内容类型”:“应用程序/json”},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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