Skip to content

Instantly share code, notes, and snippets.

@putrikarunia
Last active November 3, 2020 01:40
Show Gist options
  • Save putrikarunia/07c93e1ba9b0c8f4af417eaf4dec5a15 to your computer and use it in GitHub Desktop.
Save putrikarunia/07c93e1ba9b0c8f4af417eaf4dec5a15 to your computer and use it in GitHub Desktop.
// ======================================================
// Handle Options to pass CORS
// ======================================================
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, PUT, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, API_KEY_ID, Authorization',
'Access-Control-Max-Age': '86400',
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
// If you want to check the requested method + headers
// you can do that here.
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, PUT, OPTIONS',
},
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment