mirror of
https://github.com/zhigang1992/workers-graphql-server.git
synced 2026-01-12 22:53:37 +08:00
Merge pull request #9 from signalnerve/kristian/cors
Add CORS support for GraphQL requests
This commit is contained in:
24
src/index.js
24
src/index.js
@@ -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
20
src/utils/setCors.js
Normal 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
|
||||
Reference in New Issue
Block a user