-
Notifications
You must be signed in to change notification settings - Fork 32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to handle CORS? #12
Comments
You need to add the headers manually in your application. There's a generic tutorial for CF workers here. In Vitedge you still have control over the worker entry point so you can do something like this: import { handleEvent } from 'vitedge/worker'
addEventListener('fetch', (event) => {
if (event.request.method === 'OPTIONS') {
// Handle options request separately
event.respondWith(
new Response(null, {
headers: { ...CORS_HEADERS, Allow: ALLOWED_METHODS },
})
)
} else {
// Let Vitedge handle normal requests and modify its response to include headers
event.respondWith(
handleEvent(event).then(response => {
Object.entries(CORS_HEADERS).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
})
)
}
}) As for the headers, it depends on your need but you can try with something like this (copied from a project I have): const ALLOWED_METHODS = 'GET, POST, OPTIONS, PUT, PATCH'
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': ALLOWED_METHODS,
// iOS 12 is broken and doesn't accept only a wildcard, so specify here all the allowed headers:
'Access-Control-Allow-Headers':
'*, Accept, Content-Type, Content-Length, Accept-Encoding, Referer, Origin, User-Agent, authorization',
'Access-Control-Allow-Credentials': 'true',
// Set a cache for the OPTIONS check
'Access-Control-Max-Age': '600',
} -- |
Yes, agreed! A really good option would be adding both of them. Giving developers flexibility. This reminds me this tweet thread |
Released in |
I have a filename
getAllPosts
infunctions
file.Which return something like this
Now this works great in the same origin. But when I try to use the same API from anohter origin, it is yelling CORS errors.
What would be the best way to handle CORS in vitedge?
The text was updated successfully, but these errors were encountered: