[英]Express request body return null
I have a problem with express
POST
request,我对
express
POST
请求有疑问,
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.post('/movie/add', (req, res) => {
console.log(req.body) // {}
//
})
can someone tell me, why after sending some data like:有人可以告诉我,为什么在发送一些数据后,例如:
{
"msg":"Hello"
}
then my req.body
return me {}
?然后我的
req.body
返回我{}
? He should return me an object of my msg
value but instead of I have an empty array:/他应该给我一个我的
msg
值的 object 但我有一个空数组:/
thanks for any help!谢谢你的帮助!
You need to do two things if you want to use the request body.如果要使用请求正文,则需要做两件事。
1.in request header include Content-type application/json 1.in request header include Content-type application/json
2.in code Use middleware to parse into json. 2.在代码中使用中间件解析成json。 app.use(express.json());
app.use(express.json());
Note use app.use(express.json()) before route declartion.
Bydefault body is undefined app.use(express.json());默认情况下,正文是未定义的 app.use(express.json()); help you to defined the data while content-type application/json allow you to pass json.if you did not include content-type application/json request.body will return define empty object { }.
帮助您定义数据,而 content-type application/json 允许您传递 json。如果您没有包含 content-type application/json request.body 将返回定义空 object { }。
I think you should use body-parser http://expressjs.com/en/resources/middleware/body-parser.html我认为你应该使用 body-parser http://expressjs.com/en/resources/middleware/body-parser.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.