Complete the code to parse JSON body from the request in a Next.js route handler.
export async function POST(request) {
const data = await request.[1]();
return new Response(JSON.stringify(data));
}In Next.js route handlers, request.json() parses the JSON body from the request.
Complete the code to extract a query parameter named 'id' from the URL in a Next.js route handler.
export async function GET(request) {
const { searchParams } = new URL(request.url);
const id = searchParams.[1]('id');
return new Response(id);
}The URLSearchParams.get() method retrieves the first value of the given query parameter.
Fix the error in the code to correctly parse JSON body and handle missing fields in a Next.js POST route handler.
export async function POST(request) {
const data = await request.[1]();
if (!data.name) {
return new Response('Missing name', { status: 400 });
}
return new Response(`Hello, ${data.name}`);
}To access JSON fields like name, you must parse the body with request.json().
Fill both blanks to parse JSON body and extract a nested field 'user.email' in a Next.js POST route handler.
export async function POST(request) {
const data = await request.[1]();
const email = data.user?.[2];
return new Response(email || 'No email');
}Use request.json() to parse JSON, then access the email field from user.
Fill all three blanks to parse JSON body, extract 'username' and 'age', and check if age is over 18 in a Next.js POST route handler.
export async function POST(request) {
const data = await request.[1]();
const username = data.[2];
if (data.[3] > 18) {
return new Response(`Welcome, ${username}`);
}
return new Response('Too young', { status: 403 });
}Parse JSON with request.json(), then access username and age fields to check age.