Consider this Astro component that handles a GET request and returns a JSON response.
---
export async function get({ request }) {
return new Response(JSON.stringify({ message: 'Hello, Astro!' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
---
Check the response
What will the server respond with when this component is requested?
--- export async function get({ request }) { return new Response(JSON.stringify({ message: 'Hello, Astro!' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } --- <html> <body> <h1>Check the response</h1> </body> </html>
Remember that returning a Response object in the get function overrides the default HTML response.
When the get function returns a Response object, Astro sends that response directly. Here, it sends a JSON string with status 200 and the correct content type.
Given this Astro POST handler:
---
export async function post({ request }) {
const data = await request.json();
if (data.name) {
return new Response('Created', { status: 201 });
} else {
return new Response('Bad Request', { status: 400 });
}
}
---If the POST request body is {"name": "Astro"}, what is the response status?
--- export async function post({ request }) { const data = await request.json(); if (data.name) { return new Response('Created', { status: 201 }); } else { return new Response('Bad Request', { status: 400 }); } } ---
Check the condition that tests if data.name exists.
The handler returns status 201 when data.name is truthy, which it is in this case.
Identify the option that will cause a syntax error when defining a GET handler in Astro.
Look carefully at the parentheses and braces in the function parameter list.
Option A has a mismatched parenthesis and brace in the parameter list, causing a syntax error.
Review this Astro POST handler:
---
export async function post({ request }) {
const data = await request.json();
if (data.name === undefined) {
return new Response('Created', { status: 201 });
} else {
return new Response('Bad Request', { status: 400 });
}
}
---Why does it always return status 400 even when sending {"name": "Astro"}?
--- export async function post({ request }) { const data = await request.json(); if (data.name === undefined) { return new Response('Created', { status: 201 }); } else { return new Response('Bad Request', { status: 400 }); } } ---
Check the logic in the if condition.
The condition incorrectly treats undefined as success. It should check if data.name is defined to return 201.
Choose the correct statement about how Astro handles request and response in server-side components.
Think about what happens when you return a Response object in Astro.
Returning a Response object sends that response directly, skipping the default page rendering. Other options are incorrect because Astro does not require a 'body' object, does not auto-convert strings to JSON, and request headers are accessible.
