I am making an AJAX POST request with multiple objects to a node.js server. Although my server sends status code 200
, I am still getting the error Javascript AJAX SyntaxError: Unexpected token E in JSON at position 0
. Here is my POST request:
var company_id = "some_generic_id";
var president = "obama";
var postData = {
company_id : company_id,
president : president
};
$.ajax({
type: "POST",
url: '/api/test_link',
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
data: postData,
success: function(data, status) {
console.log('it worked!')
},
error: function(request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});
And here is my server side code:
app.post('/api/test_link', function(req, res) {
console.log('--post data--');
console.log(req.body);
/*
prints out:
--post data--
{ company_id: 'company_id', president: 'obama' }
*/
res.sendStatus(200);
});
Here’s an image from my network tab:
Does anyone know what I might be missing or why my postData
has invalid syntax?
add
res.writeHead(200, {"Content-Type": "application/json"});
at the beginning ofapp.post('/api/test_link', function(req, res) {
to specify that you wanted response as json formatRemove your
Since
res.writeHead(200, {'Content-Type': 'application/json'});
will also set your statusCodeSo it would be like this
The docs on ajax call states about
dataType
option:Since you’re not returning any data from the server, your empty data is parsed as JSON, which produces the error. Simply remove
dataType: "json"
if you’re not returning any data.I face this error if I’m not using
JSON.stringify()
:women viagra when was viagra invented average age of man taking viagra
cialis indien bezahlung mit paypal dapoxetin,cialis the cialis promise program
side effects viagra viagra alternative how to use viagra
cialis 200 mg what is it .cialis cialis trial pack
viagra contraindications statins and viagra viagra 100mg price per pill
buy cialis from canadian pharmacy buy cialis at walmart where to buy cialis