N
Nuxt5mo ago
w7a9q

async Nitro middleware

Hey, can Nitro middleware be async? I'm trying to figure it out but I get Nuxt error 402 HTTP method is not allowed. when I make middleware async.
6 Replies
w7a9q
w7a9qOP5mo ago
Anyone?
Niklas
Niklas5mo ago
can you show an example what you are doing in that middleware?
w7a9q
w7a9qOP5mo ago
export default defineEventHandler(async event => {
const body = await readBody(event)

try {
JSON.parse(body)
}
catch {
throw createError({
statusCode: 415,
statusMessage: 'Body is not JSON.',
})
}
})
export default defineEventHandler(async event => {
const body = await readBody(event)

try {
JSON.parse(body)
}
catch {
throw createError({
statusCode: 415,
statusMessage: 'Body is not JSON.',
})
}
})
w7a9q
w7a9qOP5mo ago
No description
Mähh
Mähh5mo ago
If you use readBody your route will throw a 405 in case you use any request method which does not can contain a Body e.g. a GET. Try so send a POST, PUT or some similar with body.
export default defineEventHandler(async (event) => {
if (event.method === 'GET') {
// do nothing, since we do not have a body in GET
return
}

try {
const body = await readBody(event)
} catch {
// your logic
}
})
export default defineEventHandler(async (event) => {
if (event.method === 'GET') {
// do nothing, since we do not have a body in GET
return
}

try {
const body = await readBody(event)
} catch {
// your logic
}
})
w7a9q
w7a9qOP5mo ago
That was it! Of course, thank you!
Want results from more Discord servers?
Add your server