node.js - 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?
解决方案
您可以在主服务器文件中添加以下行以进行 json 解析。
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
欲了解更多信息:转到此官方文档
推荐阅读
- entity-framework - 以前不兼容的 ef 核心迁移,如何在 CI/CD 系统中正确绕过它们?
- reactjs - Firebase 返回两个不同的输出
- python - 如何从 IPython shell 执行 Jupyter notebook?
- sql - SQLCMD 命令在 CMD 中运行,但不是作为 BAT
- matlab - 在 MATLAB 中创建时间表数组
- java - Dart/Flutter UTF-16 编码
- c# - 不更改模型的实体框架迁移
- c# - Microsoft.Azure.WebJobs.ServiceBus.dll 中的 System.InvalidOperationException
- vb.net - Public Sub New() 即 InitializeComponent 有什么用?
- c# - 如何在不阻塞所有(或其他一些)的情况下由任何并发请求触发一次?