Complete the code to create a GET handler in SvelteKit.
export async function GET({ params }) {
const data = await fetch('/api/data');
const json = await data.[1]();
return new Response(JSON.stringify(json));
}The json() method parses the response body as JSON, which is needed to handle JSON data in a GET request.
Complete the code to handle a POST request that reads JSON data from the request body.
export async function POST({ request }) {
const body = await request.[1]();
// process body
return new Response('Created', { status: 201 });
}The json() method reads the request body and parses it as JSON, which is needed to handle JSON POST data.
Fix the error in the PUT handler to correctly parse JSON from the request body.
export async function PUT({ request }) {
const data = await request.[1]();
// update resource with data
return new Response('Updated', { status: 200 });
}To update data sent as JSON, the json() method must be used to parse the request body.
Fill both blanks to create a DELETE handler that returns a 204 No Content response.
export async function DELETE({ params }) {
// delete resource identified by params.id
return new Response(null, { status: [1] });
}
// The status code [2] means no content is returned.Status code 204 means the request was successful but there is no content to return, which is standard for DELETE responses.
Fill all three blanks to create a POST handler that reads JSON, processes it, and returns a JSON response with status 201.
export async function POST({ request }) {
const data = await request.[1]();
const result = { message: 'Received', received: data };
return new Response(JSON.stringify(result), {
status: [2],
headers: { 'Content-Type': [3] }
});
}The request body is parsed as JSON using json(). The response status 201 means created. The content type header must be 'application/json' to indicate JSON response.