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.
Any help you can provide for me to understand what I am doing wrong would be greatly appreciated!
CodePudding user response:
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")