Search code examples
jqueryjsonajaxapistringify

How to formulate data object for POST request in AJAX


I have the following curl POST request to connect to a node.js API.

curl --request POST \
 --url http://localhost:3001/api/v1/login\
 --header 'Content-Type: application/json' \
 --data '{
    "username": "asdfsdfs",
    "email": "bla",
    "password": "dkasdjf333"
}'

However, I struggle with formulating the matching object for passing the POST request in AJAX for it and I get the 500 error from my API server and the browser console says: ''TypeError: Cannot read property 'replace' of undefined''. I used 2 types of data object as can be seen below.

//Version 1 which failed
 var loginData = {
 username: 'asdfsdfs',
 email: 'bla',
 password: 'dkasdjf333'
};
//version 2 which failed as well
var stringifiedJson = JSON.stringify({
 username: 'asdfsdfs',
 email: 'bla',
 password: 'dkasdjf333'
});


$.ajax({
 type: 'POST',
 url: 'http://localhost:3001/api/v1/login',
 data: loginData,
 processData: false,
 contentType: false,
 dataType: 'json'
 }).done(function(data) {
 console.log(data);
});

Solution

  • You have to update the contentType of your pist request to JSON:

    $.ajax({
        ...,
        contentType: 'application/json; charset=utf-8'
    });