首页 > 解决方案 > react app making post request with empty body

问题描述

In my onSubmit function :

    try {
    const config = {
      header: {
        'Content-Type': 'application/json'
      }
    }
    const body = JSON.stringify(newUser);
    console.log(body);
    const res = await axios.post('/api/users', body, config);
    console.log(res.data);
  }catch(err) {
    console.error(err.response.data);
  }

When i submit, my server returns 400 bad request with empty req.body

My network:

    Request header:
    Accept: application/json, text/plain, */*
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9,vi;q=0.8
    Connection: keep-alive
    Content-Length: 55
    Content-Type: application/x-www-form-urlencoded
    Host: localhost:3000
    Origin: http://localhost:3000
    Referer: http://localhost:3000/register
    Sec-Fetch-Mode: cors
    Sec-Fetch-Site: same-origin
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36

Form data:
    {"name":"bad","email":"bad@aa.com","password":"123456"}:

My server got request from react app but req.body shows empty, i tried postman and it worked perfectly. What did I do wrong?

Edit: after using bodyParser with bodyParser.json() I finally got an object from req.body

[Object: null prototype] {                                                                                             
'{"name":"bad","email":"bad@aa.com","password":"123456"}': '' } 

but still bad request. I think this unusual object causes the bad request but still don't know how to fix?

标签: node.jsreactjs

解决方案


您可以在主服务器文件中添加以下行以进行 json 解析。

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

欲了解更多信息:转到此官方文档


推荐阅读