Complete the code to define a GET endpoint in Astro.
export async function [1](context) { return new Response('Hello from GET!'); }
Astro server endpoints use uppercase HTTP method names like GET to define handlers.
Complete the code to access the request body in a POST endpoint.
export async function POST({ request }) {
const data = await request.[1]();
return new Response(JSON.stringify(data));
}request.body directly which is a stream, not parsed data.text() when expecting JSON data.To read JSON data from the request body, use request.json() which returns a promise resolving to the parsed JSON.
Fix the error in the endpoint to correctly return JSON with proper headers.
export async function GET() {
return new Response(JSON.stringify({ message: 'Hi' }), {
headers: { 'Content-Type': [1] }
});
}When returning JSON data, the Content-Type header must be application/json so clients know how to interpret the response.
Fill both blanks to create an endpoint that responds with a 404 status and a JSON error message.
export async function GET() {
return new Response(JSON.stringify({ error: 'Not found' }), {
status: [1],
headers: { 'Content-Type': [2] }
});
}Use status code 404 for 'Not found' errors and set Content-Type to 'application/json' for JSON responses.
Fill all three blanks to create a POST endpoint that reads JSON, extracts 'name', and returns a greeting.
export async function POST({ request }) {
const data = await request.[1]();
const name = data.[2];
return new Response(JSON.stringify({ greeting: `Hello, $[3]!` }), {
headers: { 'Content-Type': 'application/json' }
});
}request.text() instead of json().The endpoint reads JSON from the request body using json(), extracts the name property, and returns a greeting using that name.
