[英]Body is empty during POST method to server controller
我正在从客户端请求包含对象的发送响应,但是在后端,当我console.log(req.body)时,服务器将其显示为空白对象。
这几乎是我过去所做的示例中的复制粘贴,它发送和请求一个对象以将其发布到数据库。
这是我所拥有的:
这是在“ api.js”中
var postBaseNums = data => {
console.log(data)
fetch('/getnums', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.send())
}
“数据”是我要发送的对象,在这里我用console.log(data)来确保其不为空或不为空。
这被发送到我的/ getnums路由,该路由将它发送到后端的post方法:
postNums: (req, res, next) => {
console.log(req.body)
numSchem.create({
num: req.body
})
.then(data => res.status(201).json(data))
.catch(e => {
req.error = e
console.log(e)
next()
})
}
在这里,console.log(req.body)显示在终端“ {}”中
我尝试将主体更改为主体:数据,而不是将其字符串化,这是同一件事。
查看我的猫鼬模式后,现在出现以下错误:
numSchema validation failed: field1: Cast to String failed
for value "{}" at path "field1"
这是有道理的,因为body是一个空对象..尽管我觉得应该是一个字符串,因为在api.js中我有:body:JSON.stringify(data)
那我在做什么错呢?
假设您使用express
作为服务器或类似的服务器
安装正文解析器
npm install --save body-parser
添加中间件
//Add this where you initialize the server app
var bodyParser = require('body-parser')
app.use( bodyParser.json() )
//Your req.body is now parsed
postNums: (req, res, next) => {
console.log(req.body)
//...stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.