h3
h3 copied to clipboard
How to properly handle CORS ?
Describe the change
Hello !
I'm trying to setup few API routes in my nuxt project with nuxt hub for my students to interact with through a Python script. I've spent like 2 hours on CORS issues and it's driving me nuts.
dico_json = json.dumps(dico)
headers = {
"Content-Type": "application/json; charset=utf-8"
}
r = requests.post("route_url, data=dico_json, headers=headers)
When I set the headers option, I have CORS issues and I can't to the request. I think I tried everything :
if (isPreflightRequest(event)) {
appendCorsHeaders(event, {
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'content-type'],
})
return new Response(null, { status: 204 })
}
if (isPreflightRequest(event)) {
appendCorsPreflightHeaders(event, {
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'content-type'],
})
return new Response(null, { status: 204 })
}
const didHandleCors = handleCors(event, {
origin: '*',
preflight: {
statusCode: 204,
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'content-type'],
})
if (didHandleCors) {
return
}
I keep getting the same error again and again.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://..... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://...... (Reason: CORS request did not succeed). Status code: (null).
The python script runs from a browser running pyodide.
Can you please explain me what I'm doing wrong ? The documentation is not very helpful unfortunately, and CORS issues keep bullying me since like 15 years, everytime I think I understand the thing there's more issues I don't understand 😢
Thanks a lot ! And huge thanks for your amazing work, you guys are so amazing !!
URLs
No response
Additional information
- [X] Would you be willing to help?
There is an example here, v1: https://github.com/unjs/h3/blob/v1/examples/cors.ts For v2: https://github.com/unjs/h3/blob/main/examples/cors.ts
Hope it helps!
What I dont fully understand is what you mean by Nuxt project. Because if you have a Nuxt project (not a pure H3 project) it means you already have Nitro and within Nuxt/Nitro you just can set a route roule:
routeRules: {
'/**': {
cors: true,
},
},
Keep in mind tho that this has a "bug" for when you have a POST/PUT/DELETE route but no catch-all route it will throw a cors error. Also instead of 404 it will throw a cors error. Issue: https://github.com/nitrojs/nitro/issues/2340