0

This question might be very simple thing. But I couldnt figurout the issue in my code.

I want to send data to a node js api using jquery ajax call.

This is my node js API

.post('/createPerson', global.bodyParserJson, function (req, res, next) {           
        console.log(req.body);

      // My code going here
    })

This my ajax call from client side.

    $.ajax({
        type: 'post',
        url: serverLocation + "/api/dashboard/createPerson",
        dataType: 'json',
        data:  { Name: "John", Age: 20 },
        contentType: "application/json; charset=UTF-8",
        success: function (data) {
            console.log('Sucss');            
        },
        error: function (textStatus, errorThrown) {
           console.log('Err');

        }
    });

API is hit by ajax call, but data is not passing. It comes as empty. I try to call the api using postman and it works well which means json data comes to server side.

Can you give me a clue to find the issue in my code?

1 Answer 1

1

You have to use JSON.stringify to first serialize your object to JSON string so then your server can understand it's a JSON:

$.ajax({
        type: 'post',
        url: serverLocation + "/api/dashboard/createPerson",
        dataType: 'json',
        data:  JSON.stringify({ Name: "John", Age: 20 }),
        contentType: "application/json; charset=UTF-8",
        success: function (data) {
            console.log('Sucss');            
        },
        error: function (textStatus, errorThrown) {
           console.log('Err');

        }
    });

This should work

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.