服务器控制器的 POST 方法期间正文为空
Body is empty during POST method to server controller
我正在请求来自我的客户端的发送响应,其中包含一个对象,但是在我的后端,当我 console.log(req.body) 时,服务器显示它是一个空白对象。 .
这几乎是我过去做过的一个例子的复制粘贴,将对象发送和请求到 post 到数据库..
这是我的:
这是在'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())
}
'data' 是我要发送的对象,这里我 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) 显示在终端“{}”
我试过将 body 更改为 body: data 而不是对其进行字符串化,同样的事情。
检查我的 mongoose 架构后,我现在收到此错误:
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
}
我正在请求来自我的客户端的发送响应,其中包含一个对象,但是在我的后端,当我 console.log(req.body) 时,服务器显示它是一个空白对象。 .
这几乎是我过去做过的一个例子的复制粘贴,将对象发送和请求到 post 到数据库..
这是我的:
这是在'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())
}
'data' 是我要发送的对象,这里我 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) 显示在终端“{}”
我试过将 body 更改为 body: data 而不是对其进行字符串化,同样的事情。
检查我的 mongoose 架构后,我现在收到此错误:
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
}