Merge pull request #9 from signalnerve/kristian/cors

Add CORS support for GraphQL requests
This commit is contained in:
Kristian Freeman
2019-08-19 12:58:59 -05:00
committed by GitHub
2 changed files with 43 additions and 1 deletions

View File

@@ -1,23 +1,45 @@
const apollo = require('./handlers/apollo')
const playground = require('./handlers/playground')
const setCors = require('./utils/setCors')
const graphQLOptions = {
// Set the path for the GraphQL server
baseEndpoint: '/',
// Set the path for the GraphQL playground
// This option can be removed to disable the playground route
playgroundEndpoint: '/___graphql',
// When a request's path isn't matched, forward it to the origin
forwardUnmatchedRequestsToOrigin: false,
// Enable debug mode to return script errors directly in browser
debug: false,
// Enable CORS headers on GraphQL requests
// Set to `true` for defaults (see `utils/setCors`),
// or pass an object to configure each header
cors: true,
// cors: {
// allowCredentials: 'true',
// allowHeaders: 'Content-type',
// allowOrigin: '*',
// allowMethods: 'GET, POST, PUT',
// },
}
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)
if (graphQLOptions.cors) {
setCors(response, graphQLOptions.cors)
}
return response
} else if (
graphQLOptions.playgroundEndpoint &&
url.pathname === graphQLOptions.playgroundEndpoint

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

@@ -0,0 +1,20 @@
const setCorsHeaders = (response, config) => {
const corsConfig = config instanceof Object ? config : false
response.headers.set(
'Access-Control-Allow-Credentials',
corsConfig ? corsConfig.allowCredentials : 'true',
)
response.headers.set(
'Access-Control-Allow-Headers',
corsConfig ? corsConfig.allowHeaders : 'application/json, Content-type',
)
response.headers.set(
'Access-Control-Allow-Methods',
corsConfig ? corsConfig.allowMethods : 'GET, POST',
)
response.headers.set('Access-Control-Allow-Origin', corsConfig ? corsConfig.allowOrigin : '*')
response.headers.set('X-Content-Type-Options', 'nosniff')
}
module.exports = setCorsHeaders