When trying to get a dummy response from a POST endpoint, the call to res.json() throws a serialization error in the client :
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This is the client side :
const body = /* request body */
const res = await fetch(/* url */, {
method: 'POST',
body: JSON.stringify(body),
})
console.log(await res.json())
And this is the endpoint :
export const POST = async ({request}) => {
/* do something with the request's body */
return {
body: {a: 1}
}
}
I get the same error on the server side if I don’t stringify the body in fetch, but I can’t stringify it in the endpoint, as only plain objets (and errors) are allowed.
The outcome is the same with an empty object.
>Solution :
You have to instruct the endpoint to send JSON, otherwise it will send the associated page as server-side rendered HTML. To do that add an Accept header:
const res = await fetch(/* url */, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: JSON.stringify(body),
})