Raj Rana
Raj Rana

Reputation: 429

SyntaxError: Unexpected token o in JSON at position 1 over ajax request

i making ajax call my code looks like this

        var Data = {
        name              : $('input[name=name]').val(),
        email             : $('input[name=email]').val(),
        phoneno           : $('input[name=phoneno]').val(),
        password          : $('input[name=password]').val(),
    };
    var data = JSON.stringify(Data);
$.ajax({
        url: "/registeruser",   
        type: "POST",      
        data:  data,      
        dataType: 'json',
        contentType: 'application/json',
        success: function(response)   // A function to be called if request succeeds
        {
          console.log('responsee........', response);
        },
        error: function(jqXHR, textStatus, errorMessage) {
            console.log('handle errpe message',errorMessage); // Optional
        },
    });

i get an error on my server side nodejs
SyntaxError: Unexpected token o in JSON at position 1

my express route code

exports.registeruserController = function(req,res,next){
    console.log('sdasdasdasdasd');
 console.log('request of the user to register',req.body);
}

Upvotes: 1

Views: 3439

Answers (2)

acm14
acm14

Reputation: 1

To fix the problem just use.

JSON.stringify(res.data)

Upvotes: 0

Quentin
Quentin

Reputation: 943216

data is not JSON.

It is an object which is being implicitly converted to a string:

var data = { for: "example" };
var what_you_are_sending = "" + data;
console.log(what_you_are_sending);

The server is trying to parse it as JSON. The [ is the start of an array. The o is an error. Then it stops.


You need to convert the object to JSON with JSON.stringify.

var data = JSON.stringify({ for: "example" });
var what_you_should_send = "" + data;
console.log(what_you_should_send);

Upvotes: 3

Related Questions