[英]Send POST data with raw json with postman Express
I'm trying to log all the data and then return it as a response. 我正在尝试记录所有数据,然后将其作为响应返回。
app.post('/data', (req, res) => {
const data = req.body
console.log(data)
return res.json({
data
})
})
I'm sending data with Postman. 我正在与邮递员发送数据。 In the Body tab I have "raw" selected and "JSON (application/json)".
在“正文”选项卡中,选择了“原始”和“ JSON(应用程序/ json)”。 Headers tab is Content-Type application/json.
标头选项卡是Content-Type application / json。 I'm sending this:
我发送此:
{
"aa": 23
}
When I click send button all I get is an empty object and the data variable is undefined in my console.log. 当我单击发送按钮时,我得到的只是一个空对象,并且console.log中的数据变量未定义。 How to fix it?
如何解决? I double checked everything.
我仔细检查了一切。 It should work, but it doesn't.
它应该可以,但是不能。
Alright, I found the solution. 好吧,我找到了解决方案。
"As body-parser module is used to parse the body and urls, it should be called before any call to 'req.body...'." “由于body-parser模块用于解析正文和URL,因此应在对'req.body ...'的任何调用之前调用它。”
So I did this: 所以我这样做:
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.urlencoded())
app.use(bodyParser.json())
app.post('/data', (req, res) => {
const data = req.body
console.log(data)
return res.json({
data
})
})
And now it works fine. 现在工作正常。
It seems like you're passing an invalid value to res.JSON(). 似乎您要将无效的值传递给res.JSON()。 Try:
尝试:
return res.json(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.