简体   繁体   中英

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.

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. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:

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. 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.

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({
            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);
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM