gpt4 book ai didi

javascript - BodyParser 行为

转载 作者:行者123 更新时间:2023-12-02 17:08:40 25 4
gpt4 key购买 nike

我正在使用 cURL 发送 POST 请求:

curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }'

在我的 NodeJS 应用程序中,请求通过 bodyParser.json() 中间件。我有另一个处理请求的中间件:

app.post('/partial_Users/:page', function(req, res, next) {

var destinationPage = req.params.page;
var currentPage = req.body.currentPage;
var firstID = req.body.firstID;
console.log(req.body)
console.log(''+ currentPage + firstID)
[...]
}

在这种情况下,我希望 req.body.currentPage 返回 1。事实上,它返回“undefined”。

我注意到,当我执行 console.log(req.body) 时,我得到以下字符串:

{ '{currentPage : 1,firstID : 53d62fc6642aecf45c8b456f }': '' }

现在很明显,req.body.currentPage 将返回未定义。由于某种原因,bodyParser 无法正确解析 JSON。 req.body.firstID 也有相同的行为。

要么是我没有正确使用 BodyParser,要么是我的 JSON 请求结构不正确?

最佳答案

您需要将 -H "Content-Type: application/json" 添加到您的curl命令行,否则假定为application/x-www-form-urlencoded .

关于javascript - BodyParser 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com