My front-end javascript code shows SyntaxError: Unexpected end of JSON input
by each time running, I can locate the error comes from my fetch function.
In the beginning, I thought it was because my JSON content in the fetch request has some issue, after several guesses, I realized that is because PUT method has no response body.
My problem function as below:
function func(email) {
fetch(`/emails/${email.id}`, {
method:'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({read: true})})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
}
It is my the first time write a fetch with PUT method, When I try to deal with fetch response, I copy the GET method process, by those "then".
Actually, PUT method has no response body, so the problem comes from the then(response => response.json())
.
Then finialy, I changed the code like this, no more error.
function func(email) {
fetch(`/emails/${email.id}`, {
method:'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({read: true})})
.catch(err => console.log(err))
}
Top comments (3)
Hi Jimmy, I have not tried to reproduce the problem but there are a few things I can see in your code that are questionable.
1) The fetch function expects a maximum of 2 arguments when your code fragments have four. The last three should be within an object (see the options parameter in developer.mozilla.org/en-US/docs/W...)
Also, you function (func) has a parameter of
email
but I am not sure whereemail_id
comes from. Isid
a property ofemail
? If so, what you need isemail.id
.Finally, you might want to read: developer.mozilla.org/en-US/docs/W...
Thanks Tracy,
About my code, so sorry and happy to have your notice, I paste my code from my cs50w project, and I changed something, but didn't notice those issue. Now I made them correct enough, I think.
And the document you mentioned is great.
Fetch is a great candidate for creating a wrapper. This is a fantastic example of why.
In most scenarios, you can have your appropriate API endpoints respond with a 204 (Success, no content) status.
Then in your Fetch wrapper:
put = async <T>(url: string, body: any): Promise<T|null> => {
/// Decision logic to handle status handling of response body.
}