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

request.body possibly null – Trying to make my first Sveltekit api

enter image description here

Hi everyone!

I am trying to create my first api route with Sveltekit and I keep running into the issue on line 9 that says "request.body is possibly null" and it will not allow me to pull the id from the request.

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

Any help you can provide for me to understand what I am doing wrong would be greatly appreciated!

>Solution :

Typescript’s type checking means that it knows there isn’t a guarantee that the body field on the request object will have a value, which is why it’s showing this message. What you will need to do is to add a guard – a bit of code that checks whether request.body has a value and if not, does some kind of error handling or alternate processing.

Looking at your code, without an id you probably won’t be wanting to do much so the guard can just throw an error, preferably with a useful message like "Invalid request: Need to supply 'id' field in request body".

The below snippet gives an example of a guard clause. You might need to also verify that .get("id") isn’t undefined.

const data = request.body;
if (data === undefined) {
  throw new Error("Invalid request: Need to supply 'id' field in request body");
}
const id = data.get("id")
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