我是一个初学者,由于这个问题,我已经好几天不停地动脑筋了。
基本上,我只想使用node和express发出发布请求。该对象将动态创建,但这是我的硬编码示例。 myObj包含一个数组,因为稍后我想在服务器端为每个项目向数据库中插入一个。
let myObj = {
id: 50,
damage_type: ["missing", "broken", "light"]
}
// Parse myObj to JSON string to be sent
let myjsonObj = JSON.stringify(myObj);
console.log(myjsonObj );
// {"poi":50,"damage_type":["missing","broken","light"]}
postDamage(myjsonObj )
function postDamage(damage) {
$.post({
type: 'POST',
url: '/damage',
data: damage
}).
done(function (damage) {
// Do things
}
router.post('/damage', (req, res) =>
{
let data = req.body;
console.log(data)
// This is what I get in the node terminal which is nonsense, I cannot work with
{ '{"id":50,"damage_type":["missing","broken","light"]}': '' }
I expect it to look like {"id":50,"damage_type":["missing","broken","light"]}
So I can loop through the damage_type creating new objects with this structure
createSQLfunction({id:50, damage_type:"missing"})
});
如果我不对myObj进行字符串化,则节点终端正在打印
{poi:'50', 'damage_type[]: [ 'missing','broken','light']}
额外的[]来自哪里?!
不能将对象内部的数组发送到服务器端我在做什么错了?
答案 0 :(得分:0)
从jquery网站上:
数据
类型:PlainObject或字符串或数组
要发送到 服务器。如果还不是字符串,则将其转换为查询字符串。 它被附加到GET请求的URL上。参见processData选项 防止这种自动处理。对象必须是键/值对。如果 value是一个数组,jQuery使用相同的键序列化多个值 基于传统设置的值(如下所述)。
traditional
设置似乎是对其进行URL编码为key[]=val1&key[]=val2
还是仅仅是key=val1&key=val2
。您可以尝试一下,YMMV。
或者您可以使自己的生活变得更轻松,只需自己序列化json,而不用弄乱jquery的url编码。
*编辑:回答关于最佳做法的问题:在JavaScript表单提交流行之前,提交表单的两种标准方法是application/x-www-form-urlencoded
或multipart/form-data
。如果您有要使用表单提交的文件,则通常使用后者。
但是,随着JavaScript XHR(ajax)表单提交的出现,使用JSON代替这两种格式中的任何一种变得越来越普遍/流行。因此,在提交数据时执行data: JSON.stringify(object)
之类的操作,然后指示服务器读取JSON,绝对没有任何错误。
实际上,它可能既容易又快速。这是一种非常流行的方法,因此不必担心会违反现代最佳实践。