Complete the code to define a GET route in a Vue server API.
export default defineEventHandler(async (event) => {
if (getMethod(event) === '[1]') {
return { message: 'Hello from API' }
}
})The GET method is used to fetch data from the server. Here, we check if the request method is GET to respond accordingly.
Complete the code to extract a query parameter named 'id' from the request URL.
export default defineEventHandler((event) => {
const id = getQuery(event).[1]
return { id }
})The getQuery(event) returns an object of query parameters. Accessing id gets the value of the 'id' parameter.
Fix the error in the code to correctly read JSON data from a POST request body.
export default defineEventHandler(async (event) => {
if (getMethod(event) === 'POST') {
const data = await [1](event)
return { received: data }
}
})The readBody(event) function reads and parses the JSON body of the request in Vue server API.
Fill both blanks to create a route handler that responds only to DELETE requests and returns a success message.
export default defineEventHandler((event) => {
if (getMethod(event) === '[1]') {
return { message: '[2]' }
}
})The route checks if the request method is DELETE and returns a success message confirming deletion.
Fill all three blanks to create a route that reads a 'name' from the POST body and returns a greeting.
export default defineEventHandler(async (event) => {
if (getMethod(event) === '[1]') {
const body = await [2](event)
return { greeting: `Hello, ${body.[3]!` }
}
})This code handles POST requests, reads the JSON body using readBody, and accesses the 'name' property to create a greeting.