N
Nuxt12mo ago
cosbgn

Did anyone manage to handle CORS with h3/nuxt/nitro?

I'm trying everything like this:
export default defineEventHandler( async (event) => {
const cors_headers = {
origin: '*',
preflight: { statusCode: 204 },
methods: '*'
}
await handleCors(event, cors_headers)
await appendCorsHeaders(event, cors_headers)
await appendResponseHeaders(event, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "*"
})
return "hello"
})
export default defineEventHandler( async (event) => {
const cors_headers = {
origin: '*',
preflight: { statusCode: 204 },
methods: '*'
}
await handleCors(event, cors_headers)
await appendCorsHeaders(event, cors_headers)
await appendResponseHeaders(event, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "*"
})
return "hello"
})
I always get: request blocked: (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
11 Replies
manniL
manniL12mo ago
There is a CORS route rule which you could use 🙂
manniL
manniL12mo ago
GitHub
nitro/src/options.ts at aabdc9c5c78c011a212c754058160ed23391361d · ...
Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer. - unjs/nitro
manniL
manniL12mo ago
but handleCors should cover it all already
manniL
manniL12mo ago
you don't even need to pass options as the defaults should cover "allow all"
TameShinji
TameShinji11mo ago
I'm also running into this issue, and handleCors isn't handling it at all
manniL
manniL11mo ago
Can you provide a reproduction? Also the h3 docs were updated on it
TameShinji
TameShinji11mo ago
I realize my situation isn't exactly identitcal, as I am using h3, but not nitro
manniL
manniL11mo ago
Should still work with h3 only though
TameShinji
TameShinji11mo ago
I nuked my entire project and restarted and now it’s working Not helpful at all, but I’m on a time crunch 😬
manniL
manniL11mo ago
Maybe was an old h3 version? Anyway happy it helps

Did you find this page helpful?