An ajax function from jQuery
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
console.log( "Data Saved: " + msg );
});
And this is a request using a fetch API
const data = { name: "John", data: "Boston" };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data,
};
const response = await fetch('/api ',options);
const responseData = await response.json();
console.log(responseData);
Also how come this fetch implementation is producing an error in my node terminal ?
If I use a digit instead of ‘Boston’ for example the Unexpected token changes to ‘<‘ .
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Is there anything I should watch out for between these two?
data of ajax and body of fetch?
(I am not using them simultaneously the way)
2
Answers
You claim you are sending JSON.
data
is an object, not JSON.When it gets forced into a string (because it isn’t a data type recognised by
fetch
so it gets converted to a string automatically) it becomes"[object Object]"
which is still not JSON. (The[
starts an array and then theo
is an error).If you want to send JSON, you need to convert to the object to JSON yourself. Use
JSON.stringify
.Also note that while the server-side code appears to be able to handle JSON input, jQuery sends
application/x-www-form-urlencoded
data, not JSON.So to match that you would need:
From the documentation we can see that…
fetch
doesn’t do that. But separately, you’ve said you’re sending JSON by includingContent-Type: application/json
as a header, but you aren’t doing that (and your jQuery code doesn’t do that either, it sends URI-encoded data).You have to do it yourself. If you want to send JSON, use
JSON.stringify
:If you want to send URI-encoded data, use
URLSearchParams
:If you want to send standard form encoding, use
FormData
(exactly like the above, but withFormData
instead ofURLSearchParams
.Because your object is being coerced to a string, and it coerces to
"[object Object]"
, which is invalid JSON as of theo
.Side note: Your
fetch
code is falling prey to a footgun in the API:fetch
only rejects its promise on network error, not on HTTP error. You can’t assume that a fulfilled promise fromfetch
means your request was successful, you have to check: