我使用body-parser中间件在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
};
端点期望的数据如下所示:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
当我通过Postman发送这些数据时,一切正常。 req.body.options
存在并且是一个数组。但是,当我在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);
}
});
我收到400错误,报告缺少选项。打印的req.body看起来像这样:
{ 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'
我之前从未遇到过这个问题。问题不在于快递,因为邮递员使用相同的数据并且它有效。我能想到的唯一问题在于,请求是通过安全连接从iframe提供的,但这没有用。
我不知道导致此错误的原因。