2

jQuery ajax post generates an errror "Unexpected token : [newline]" on JSON response from Node + Express:

SyntaxError {stack: "SyntaxError: Unexpected token :↵    at eval (nativ…st:3000/javascripts/jquery-1.10.1.min.js:6:18626)", message: "Unexpected token :"}

On the server:

app.post('/api/sav', function(req, res, next) {
  var result = {"status": "success"};        
    res.send(JSON.stringify(result))  // this works

    //res.type('json');  // this has no effect  
    //res.type('application/json');  // this has no effect      
    //res.send(result); // this fails but should work, no?
    //res.json(result); // this fails but should work, no?
});

And on the client

$.ajax({
     type: "POST",
     url: '/api/sav',
     data: content,
     success: function(data, textStatus, jqXhr) {
       console.log(data);
     },
     error: function(jqXHR, textStatus,errorThrown ) {
        console.log(textStatus);
        console.log(errorThrown);
     },
     dataType: 'json'
 });

The server response seems identical in each case: enter image description here

In the past, I've been able to use res.send(object) just fine without explicitly stringifying. Can't think of any express.js settings that I've forgotten to set here.

syntax error: unexpected token <

Community
  • 1
  • 1
prototype
  • 7,249
  • 15
  • 60
  • 94
  • 2
    you're really mixing apples and oranges. the ajax request is going to `/api/sav` but the node code has `/api/myroute`. you also didn't mention what `content` is in your ajax request. when I pasted the code into sublimetext, sublimelinter picked up that there's a trailing whitespace on the line with `var result = {"status": "success"};` which could possibly be the problem if the ajax request was actually reaching `/api/myroute`. I hope that helps – Stephen Apr 17 '14 at 00:06

0 Answers0