问题描述
我正在做的客户:
$.ajax({
url: '/create',
type: 'POST',
data: JSON.stringify({
theme: "somevalue",
snippet: {
name: "somename",
content: "somevalue"
}
}),
complete: function (response)
{
}
});
在服务器(node.js/express.js
)上我正在做
on the server ( node.js/express.js
) I'm doing :
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"}}': ''
}
这真的很奇怪,我找不到我做错的事情.有什么想法吗?
This is really weird and I can't find what I'm doing wrong. Any ideas?
来自 BodyParser模块文档:
返回仅解析经过urlencoded主体的中间件.这个解析器 仅接受主体的UTF-8编码并支持自动 gzip压缩和deflate编码.
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.
将包含已解析数据的新主体对象填充到 中间件(即主体)之后的请求对象.该对象将 包含键值对,其中值可以是字符串或数组 (当extended为false时)或任何类型(当extended为true时).
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
Remove Stringify in your client side
$.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);
});
这篇关于Express.js:将数据作为req.body对象的KEY而不是req.body的VALUE进行发布吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!