[英]Array is flattened when it's sent through AJAX jQuery request
I have the following endpoint written in Express, using the body-parser middleware. 我使用主体解析器中间件在Express中编写了以下端点。
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this: 端点期望的数据如下所示:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. 当我通过邮递员发送此数据时,一切正常。 req.body.options
exists and is an array. req.body.options
存在并且是一个数组。 However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different: 但是,当我在jQuery AJAX调用中执行完全相同的操作时,结果明显不同:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. 我收到400错误,报告缺少选件。 The printed req.body looks like this: 印刷的需求主体如下所示:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. 我以前从未遇到过这个问题。 The problem is not in express, as a request through Postman using the same data and it works. 问题并不明确,因为邮递员使用相同的数据进行了请求,并且可以正常工作。 The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense. 我能想到的唯一问题在于,该请求是通过通过安全连接提供服务的iframe发出的,但这没有任何意义。
I have no idea what causes this error. 我不知道是什么原因导致此错误。
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify. 根据这 两个问题,解决了该问题,在AJAX请求上指定了标头类型并进行了字符串化。
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.