Complete the code to create a simple API route handler in Next.js.
export default function handler(req, res) {
res.status(200).json({ message: [1] })
}The API route sends a JSON response with a message string. The message must be a string literal inside quotes.
Complete the code to check the HTTP method in the API route.
export default function handler(req, res) {
if (req.method === [1]) {
res.status(200).json({ message: "GET request received" })
} else {
res.status(405).end()
}
}The code checks if the request method is GET to handle GET requests specifically.
Fix the code in the API route to correctly access JSON data from a POST request.
export default async function handler(req, res) {
if (req.method === "POST") {
const data = req.[1]
res.status(200).json({ received: data })
} else {
res.status(405).end()
}
}In Next.js API routes, the request body is automatically parsed as JSON. Access it via req.body.
Fill both blanks to create an API route that responds with a JSON object containing a query parameter.
export default function handler(req, res) {
const name = req.query.[1]
res.status(200).json({ greeting: `Hello, $[2]!` })
}The query parameter is accessed as req.query.name, and the greeting interpolates that variable using ${name}.
Fill all three blanks to create an API route that handles POST requests and returns the posted data with a status message.
export default async function handler(req, res) {
if (req.method === [1]) {
const data = req.[2]
res.status(200).json({ status: [3], data })
} else {
res.status(405).end()
}
}The API route checks for POST method, accesses req.body, and returns a success status with the data.