简体   繁体   English

快递请求正文返回 null

[英]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.

view example here在此处查看示例

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 { }。

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

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