gpt4 book ai didi

javascript - 如何通过 Postman 将 JSON 发送到 NodeJS Express Server?

转载 作者:行者123 更新时间:2023-11-30 09:52:32 24 4
gpt4 key购买 nike

我正在尝试从 Chrome 应用“Postman”通过 POST 发送一个 JSON 对象。

如果我将 header 设置为'Content-Type: text/plain',那么另一端的输出是一个空对象:

{}

如果我将 header 设置为 Content-Type: application/json,我会收到以下响应...

'Error: invalid json'.

键设置为ingredients,值设置为:

{ ["name" : "num1", "quantity" : "5"], ["name" : "num2", "quantity" : "2"], [ "name" : "num3", "quantity" : "8"]}

我在这里捕获了它:

router.post('/add', jsonParser, function( req, res ) {

if (!req.body) return res.sendStatus(400);
console.log( req.body );
});

最佳答案

您的 JSON 无效。重组为既能正确解析又能让你继续工作的东西。下面的示例应该可以正常工作,您的对象数组存储在 ingredients...

{
"ingredients": [{
"name": "num1",
"quantity": "5"
}, {
"name": "num2",
"quantity": "2"
}, {
"name": "num3",
"quantity": "8"
}]
}

您可以随心所欲地切换它,只要确保它能够解析即可。 JSONLint会成为你的 friend 。即使是没有命名标识符的普通数组也可以工作,而且我看得越多,它看起来就好像您只是将 {}[] 语法倒过来...

[{"name": "num1", "quantity": "5"}, {"name": "num2","quantity": "2"}, {"name": "num3","quantity": "8"}]

关于javascript - 如何通过 Postman 将 JSON 发送到 NodeJS Express Server?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35652195/

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