user1547174 user1547174 - 10 days ago 5
jQuery Question

Object property changes after AJAX POST request

I am building an app using node + express and I am making a POST request where I post an array of strings. However, when I print out the request body on the server side, the object property changes:

var test_array = ['1', '2', '3', '4'];

$.ajax({
type: 'POST',
url: 'some_url/',
headers: {
'x-access-token': 'some_token'
},
data: {
myArray: test_array
},
success: function () {
console.log('success!');
},
error: function (a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
});


HOWEVER, when i log out the request on the server side, I get:

console.log(req.body);


{ 'myArray[]': [ '1', '2', '3', '4' ] }


Does anyone know why
myArray
became
myArray[]
on the server side? Thanks in advance!

Answer

You can add contentType: 'application/json' and dataType: 'json' in the ajax post request to post the data as json to the server as below

var test_array = ['1', '2', '3', '4'];

$.ajax({
  type: 'POST',
  url: 'some_url/',
  headers: {
        'x-access-token': 'some_token'
  },
  contentType: 'application/json',
  dataType: 'json',
  data: {
    myArray: test_array
  },
  success: function () {
    console.log('success!');
  },
  error: function (a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
  }
});
Comments