unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability
https://h3.unjs.io/
MIT License
3.69k stars 219 forks source link

How to properly handle CORS ? #902

Open arkhaiel opened 1 month ago

arkhaiel commented 1 month ago

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