gpt4 book ai didi

node.js - postman 发送原始 JSON 帖子的奇怪响应( Node js)

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:17 26 4
gpt4 key购买 nike

我正在尝试使用原始 json 执行 POST 请求。

在“正文”选项卡中,我使用此正文选择了“原始”:

{
"name": "book"
}

在 Node js 端,我正在执行 res.send(JSON.stringify(req.body))

router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}

在 postman 回复中我收到:

{"{\n\"name\": \"book\"\n}":""}

当预期类似的时候

{"name":"book"}

不知道 - 原因在哪里?

最佳答案

您需要使用 Express JSON 正文解析器,使用

安装
npm install body-parser; 

然后:

const bodyParser = require('body-parser');
app.use(bodyParser.json());

执行此操作后,JSON 数据将被正确解析,并且当您将其发送回时,它将正确呈现。

还要确保您的 Postman 请求中的 Content-Type header 设置为“application/json”(转到“ header ”并添加一个值为“application/json”的新“Content-Type” header )

这是一个简单的 Express 应用程序,它将回显任何 JSON POST:

const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')

app.use(bodyParser.json());

app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})

app.listen(port);
console.log(`Serving at http://localhost:${port}`);

关于node.js - postman 发送原始 JSON 帖子的奇怪响应( Node js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58062558/

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