I have this code in javascript
var url = 'http://mydomain.com:3000';
url += "/user";
jQuery.ajax({
url: url,
type: "GET",
dataType: "jsonp",
async: false,
success: function (data) {alert(1);
console.log(data);
}
});
where my site runs on http://mydomain.com:80 so they are not in the same server.
http://mydomain.com:3000 is served by nodejs with the code
app.get('/user',function(req,res){
var result = {
result:-1
};
res.json(result);
res.writeHead(200, {"Content-Type": "application/json"});
});
When I call the ajax I get from the chrome preview response
{
"result": -1
}
but in the console of the javascript I got the error
Uncaught SyntaxError: Unexpected token : user:2
and I don't get any alert message.
I even tried in nodejs
res.end("'"+JSON.stringify(result)+"'");
and the chrome preview response is
'{"result":-1}'
and the console error is gone but still the alert is not triggered
res.json() sends the response immediately. You have to set headers before using this.
res.json(result);
res.writeHead(200, {"Content-Type": "application/json"}); //Response already sent before.
So res.writeHead() does not set header in response. The error that you are getting means that there is some illegal character code in your response.
Uncaught SyntaxError: Unexpected token : user:2
Try setting headers before, browser will then correctly identify your message as JSON.
Update
On checking your code again I saw that you are sending response as res.json() but in your AJAX recieving it as jsonp. The two are different json and jsonp. There is a res.jsonp() you can use in node or change datatype in your AJAX query as json.