How to get params of a POST endpoint with SvelteKit?

Viewed 3952

The SvelteKit documentation gives an example for how to write GET endpoints with parameters...

export async function get({ params }) { /* [...] */ }

...and how to write POST endpoints without parameters...

export function post(request) { /* [...] */ }

How do I write POST endpoints with parameters? More precisely: What is the function signature that I have to use if I want to access both the parameters and the request body in my endpoint?

2 Answers

You can do the same thing for POST request handling!

export function post({ params, body }) { /* [...] */ }

All endpoint handlers are of type RequestHandler, which are functions that take in a ServerRequest and have essentially the same function signature. POST requests also have the body property on the request object, which is parsed according to the Content-Type header.

For anyone else who might be stuck with the GET method. The parameters for the GET request has changed. Params has been replaced by url.

export async function GET({url}) {...}

The query parameters can then be extracted from the searchParams objects.

const text = url.searchParams.get('text');
Related