Initial code spike towards fixing CORS headers

This commit is contained in:
Kristian Freeman
2019-08-19 11:41:29 -05:00
parent 0b6db7c94a
commit e94a260e30
2 changed files with 16 additions and 1 deletions

View File

@@ -1,5 +1,6 @@
const apollo = require('./handlers/apollo')
const playground = require('./handlers/playground')
const setCors = require('./utils/setCors')
const graphQLOptions = {
// Set the path for the GraphQL server
@@ -17,7 +18,12 @@ const handleRequest = request => {
const url = new URL(request.url)
try {
if (url.pathname === graphQLOptions.baseEndpoint) {
return apollo(request, graphQLOptions)
const response =
request.method === 'OPTIONS'
? new Response('', { status: 204 })
: await apollo(request, graphQLOptions)
setCorsHeaders(response)
return response
} else if (
graphQLOptions.playgroundEndpoint &&
url.pathname === graphQLOptions.playgroundEndpoint

9
src/utils/setCors.js Normal file
View File

@@ -0,0 +1,9 @@
const setCorsHeaders = response => {
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Credentials', 'true')
response.headers.set('Access-Control-Allow-Methods', 'GET,POST')
response.headers.set('Access-Control-Allow-Headers', 'application/json, Content-type')
response.headers.set('X-Content-Type-Options', 'nosniff')
}
module.exports = setCorsHeaders