POST的数组数据将被解析为JSON [英] POST array data to Express gets parsed out as JSON
问题描述
我的应用程序是使用Express的Node.js。
My app is Node.js using Express.
使用jQuery POST从客户端发送此测试数据:
Sending this test data from my client using jQuery POST:
{
title: 'hello',
notes: [
{title: 'note 1'},
{title: 'note 2'}
]
}
这是我的服务器代码的结果:
And this is the result in my server code:
{ title: 'hello', notes: { '0': { title: 'note 1' }, '1': { title: 'note 2' } } }
我想得到一个笔记数组作为数组插入我的数据库。我缺少什么?
I want to get the array of notes to insert into my DB as an Array. What am I missing?
由于我无法自己添加一个答案8小时(wtf?)但是它没有真正回答为什么Express.bodyParser不正确解析JSON
As I can't add an answer myself for 8 hours (wtf?) BUT it does not really answer why Express.bodyParser does not parse JSON correctly
Ok I 可以通过使用以下方式使其工作:
Ok I can get it to work by using:
JSON.stringify ( data )
使用
on the client then server side using
JSON.parse( req.rawBody )
这确实感到错了,为什么Express.bodyParser不能正确解析JSON?
This does feel wrong and why does Express.bodyParser not parse JSON correctly?!
推荐答案
在您的客户端:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/endpoint'
});
在您的服务器上:
console.log('POST: ',req.body);
问题是在发送数据之前jQuery会丢失数据。如果您设置正确的MIME类型,则不会让您免费。
The problem is jQuery mucks around with your data before sending it. If you set the right MIME type, than it leaves you free.
这篇关于POST的数组数据将被解析为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!