0
0
NextJSframework~10 mins

Why API routes serve backend logic in NextJS - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple API route handler in Next.js.

NextJS
export default function handler(req, res) {
  res.status(200).json({ message: [1] })
}
Drag options to blanks, or click blank then click option'
Aconsole.log('Hello')
BHello from API!
C"Hello from API!"
Dres.send('Hello')
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string message
Using console.log instead of sending a response
2fill in blank
medium

Complete the code to check the HTTP method in the API route.

NextJS
export default function handler(req, res) {
  if (req.method === [1]) {
    res.status(200).json({ message: "GET request received" })
  } else {
    res.status(405).end()
  }
}
Drag options to blanks, or click blank then click option'
A"GET"
B"POST"
C"PUT"
D"DELETE"
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names without quotes
Checking for the wrong HTTP method
3fill in blank
hard

Fix the code in the API route to correctly access JSON data from a POST request.

NextJS
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()
  }
}
Drag options to blanks, or click blank then click option'
Abody
Btext
Cjson
Dparse
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.json() (for app router route handlers)
Calling req.body() as a method
4fill in blank
hard

Fill both blanks to create an API route that responds with a JSON object containing a query parameter.

NextJS
export default function handler(req, res) {
  const name = req.query.[1]
  res.status(200).json({ greeting: `Hello, $[2]!` })
}
Drag options to blanks, or click blank then click option'
Aname
Buser
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for query and greeting
Accessing query parameters incorrectly
Forgetting ${} around the variable in the template literal
5fill in blank
hard

Fill all three blanks to create an API route that handles POST requests and returns the posted data with a status message.

NextJS
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()
  }
}
Drag options to blanks, or click blank then click option'
A"POST"
Bbody
C"success"
D"GET"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong HTTP method string
Using req.json() instead of req.body
Wrong status message