0

So client-side-js just send POST with JSON object

$.ajax({
    type: 'POST',
    url: '/onadd',
    data: addJsonObj.toJSON,
    success: function(){
        console.log("Task added!", data);
    }
});

to my nodeJS server.

I see my incoming request on nodeJS server. So how can I parse JSON object from request on my nodeJS server? Need smth like that:

if(request.method == 'POST' && request.url == '/onadd'){
    var jsonObj = JSON.parse(request.body);  //can't parse JSON here!(
    console.log(jsonObj.task);   
    console.log('hoorayyyy!!!!!!');  //got this!
}

2 Answers 2

1

You have to declare data type

$.ajax({
        type: 'POST',
        url: '/onadd',
        data: addJsonObj.toJSON,
        dataType: "json",
        success: function(){
            console.log("Task added!", data);
        }
});
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. i hope i helped
0

You need to set the dataType like @Matthieu suggested:

$.ajax({
    type: 'POST',
    url: '/onadd',
    data: JSON.stringify(addJsonObj),
    dataType: 'json',
    success: function(){
        console.log('Task added!', data);
    }
});

You also need to stream the request body like so:

if(request.method == 'POST' && request.url == '/onadd'){
    var json = '';
    request.on('data', function (chunk){
        json += chunk.toString('utf8');
    });
    request.on('end', function (){
       console.log(json);
       var jsonObj = JSON.parse(json);
       console.log(jsonObj.task);
    });
}

9 Comments

undefined:0 ^ SyntaxError: Unexpected end of input
@Spacemaster what does the console.log I just added say?
@Spacemaster In the front-end log what addJsonObj.toJSON is. Perhaps that isn't what you meant to send.
So I sended this JSON object { isCompleted: fixed, task: task, date: dateStr }
Is addJsonObj.toJSON a string or an object?
|

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.