1.仅配置app.use(express.json())未配置app.use(express.urlencoded({ extended: false }))
// 配置解析application/json格式数据的内置中间件
app.use(express.json())
问题:未配置处理application/x-www-form-urlencoded格式数据的中间件
解决方法:配置app.use(express.urlencoded({ extended: false }))
// 配置解析application/json格式数据的内置中间件
app.use(express.json())
// 配置解析application/x-www-form-urlencoded格式数据的内置中间件
app.use(express.urlencoded({ extended: false }))
2.上述两个中间件都配置了,但获取res.body还是为{}
问题:请求头未配置数据格式,默认数据格式为application/json
解决:
前端发送请求时,设置请求头“content-type”为“application/x-www-form-urlencoded”
同时在服务端配置跨域请求允许的访问头
app.use(function(req,res,next){
res.header('Access-Control-Allow-Headers', 'Content-Type')
next()
})
如果不配置res.header('Access-Control-Allow-Headers', 'Content-Type')
,则会出现以下提示content-type is not allowed
。
3.若请求体res.body为undefined,可能是因为上述两个中间件都未配置。