Complete the code to read the JSON body from a fetch request in a SvelteKit endpoint.
export async function POST({ request }) {
const data = await request.[1]();
return new Response(JSON.stringify(data));
}Use request.json() to parse the JSON body from the request.
Complete the code to extract a URL search parameter named 'id' from the request URL in a SvelteKit endpoint.
export async function GET({ url }) {
const id = url.searchParams.[1]('id');
return new Response(`ID is ${id}`);
}has returns a boolean, not the value.set or append modifies parameters instead of reading.The get method retrieves the value of a search parameter by name.
Fix the error in the code to correctly parse form data from a POST request in a SvelteKit endpoint.
export async function POST({ request }) {
const form = await request.[1]();
const name = form.get('name');
return new Response(`Name is ${name}`);
}request.json() when the body is form data causes errors.request.text() returns raw text, not parsed form data.Use request.formData() to parse form data from the request body.
Fill both blanks to parse JSON from the request and return a JSON response with a message.
export async function POST({ request }) {
const data = await request.[1]();
return new Response(JSON.stringify({ message: data.[2] }), {
headers: { 'Content-Type': 'application/json' }
});
}text instead of json causes parsing errors.Use request.json() to parse JSON, then access the name property from the parsed data.
Fill all three blanks to parse URL parameters and JSON body, then return a combined JSON response.
export async function POST({ url, request }) {
const id = url.searchParams.[1]('id');
const data = await request.[2]();
return new Response(JSON.stringify({ id: id, name: data.[3] }), {
headers: { 'Content-Type': 'application/json' }
});
}has instead of get for URL parameters.text instead of json for parsing body.Use get to read the URL parameter, json to parse the request body, and access the name property from the JSON data.