Complete the code to define an API route that returns JSON data.
export async function GET() {
return new Response(JSON.stringify({ message: 'Hello' }), {
headers: { 'Content-Type': '[1]' }
});
}The API route must set the Content-Type header to application/json to indicate it returns JSON data.
Complete the code to parse JSON data from a POST request in an API route.
export async function POST({ request }) {
const data = await request.[1]();
return new Response(JSON.stringify({ received: data }), {
headers: { 'Content-Type': 'application/json' }
});
}The request.json() method parses the JSON body from the POST request.
Fix the error in the API route that should return a 404 status when data is not found.
export async function GET() {
const data = null;
if (!data) {
return new Response(null, { status: [1] });
}
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
}The status code 404 means 'Not Found', which is appropriate when data is missing.
Fill both blanks to create an API route that reads a query parameter and returns it in JSON.
export async function GET({ url }) {
const name = url.searchParams.[1]('name');
return new Response(JSON.stringify({ greeting: `Hello, ${name}` }), {
headers: { 'Content-Type': '[2]' }
});
}The get method retrieves the value of a query parameter. The Content-Type must be application/json for JSON responses.
Fill all three blanks to create an API route that accepts JSON, modifies it, and returns the updated JSON.
export async function POST({ request }) {
const data = await request.[1]();
data.timestamp = Date.[2]();
return new Response(JSON.stringify({ updated: data }), {
headers: { 'Content-Type': '[3]' }
});
}The json() method parses the request body as JSON. Date.now() returns the current timestamp. The response Content-Type must be application/json.