gpt4 book ai didi

json - Express.js : POST data as KEY of a req. body 对象而不是 req.body 的 VALUE?

转载 作者:搜寻专家 更新时间:2023-10-31 23:47:30 25 4
gpt4 key购买 nike

来 self 正在做的客户:

$.ajax({
url: '/create',
type: 'POST',
data: JSON.stringify({
theme: "somevalue",
snippet: {
name: "somename",
content: "somevalue"
}
}),
complete: function (response)
{

}
});

在服务器上(node.js/express.js)我在做:

var app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
.......
...
app.post('/create', function (req, res)
{
var dataReceived = req.body;
});

我希望 dataReceived 的值是:

{
"theme" : "somevalue",
"snippet" : {
"name": "somename",
"content" : "somevalue"
}
}

dataReceived 的值是:

{ 
'{"theme":"somevalue","snippet":"name":"somename","content":"somevalue"}}': ''
}

这真的很奇怪,我找不到我做错了什么。有什么想法吗?

来自 BodyParser module documentation :

bodyParser.urlencoded(options)

Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

这与我的问题有关吗?

最佳答案

在你的客户端移除 Stringify

$.ajax({
url: '/create',
type: 'POST',
data: {
theme: "somevalue",
snippet: {
name: "somename",
content: "somevalue"
}
},
complete: function (response)
{

}
});

或者在服务端重新解析

app.post('/create', function (req, res)
{
var dataReceived = JSON.parse(req.body);
});

关于json - Express.js : POST data as KEY of a req. body 对象而不是 req.body 的 VALUE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201823/

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