Complete the code to export a GET handler in a SvelteKit server route.
export const GET = async (event) => {
return new Response('Hello from server route!');
};
// This is a [1] exportIn SvelteKit server routes, handlers like GET are exported as named exports.
Complete the code to read a URL parameter named 'id' from the event in a GET handler.
export const GET = async (event) => {
const id = event.url.searchParams.get('[1]');
return new Response(`ID is ${id}`);
};The URL parameter name to get is 'id', so we use event.url.searchParams.get('id').
Fix the error in the POST handler to parse JSON body from the request.
export const POST = async (event) => {
const data = await event.request.[1]();
return new Response(JSON.stringify(data));
};To parse JSON from the request body, use event.request.json().
Fill both blanks to create a server route that returns JSON with status 200.
export const GET = async (event) => {
return new Response(JSON.stringify({ message: 'OK' }), {
[1]: 200,
[2]: { 'Content-Type': 'application/json' }
});
};The Response constructor uses 'status' for HTTP status code and 'headers' for HTTP headers.
Fill all three blanks to create a POST handler that reads JSON, modifies it, and returns updated JSON.
export const POST = async (event) => {
const data = await event.request.[1]();
data.updated = true;
return new Response(JSON.stringify([2]), {
[3]: { 'Content-Type': 'application/json' }
});
};Use event.request.json() to parse JSON, return the modified data object, and set headers for JSON content.