Complete the code to export a GET route handler that returns a JSON response.
export async function GET(req: Request) {
return new Response(JSON.stringify({ message: [1] }), {
headers: { 'Content-Type': 'application/json' },
});
}The response body must be a JSON string, so the message needs to be a string literal inside JSON.stringify.
Complete the code to parse JSON from the POST request body.
export async function POST(req: Request) {
const data = await req.[1]();
return new Response(JSON.stringify({ received: data }), {
headers: { 'Content-Type': 'application/json' },
});
}To parse JSON from the request body, use req.json() which returns a promise resolving to the parsed object.
Fix the error in the route handler by correctly setting the status code in the Response constructor.
export async function DELETE(req: Request) {
return new Response(null, { status: [1] });
}A DELETE request that succeeds but returns no content should use status code 204 (No Content).
Fill both blanks to create a route handler that reads a query parameter 'id' from the URL and returns it in JSON.
export async function GET(req: Request) {
const url = new URL(req.url);
const id = url.[1].get('[2]');
return new Response(JSON.stringify({ id }), {
headers: { 'Content-Type': 'application/json' },
});
}The URL object has a searchParams property to access query parameters. The parameter name is 'id'.
Fill all three blanks to create a POST route handler that reads JSON body, extracts 'name', and returns a greeting message.
export async function POST(req: Request) {
const data = await req.[1]();
const name = data.[2] ?? 'Guest';
return new Response(JSON.stringify({ message: `Hello, [3]!` }), {
headers: { 'Content-Type': 'application/json' },
});
}Use req.json() to parse JSON body, access the 'name' property, and use template literal syntax ${name} inside the string.