Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sveltekit : Unable to access a POST endpoint's reponse body as json

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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),
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading