diff --git a/src/app.js b/src/app.js index b835c8921bcfc64c08d6175f610e6532b7d5d33c..54fe5addc884fb12396b4f29d700d03b7c6f3b7c 100644 --- a/src/app.js +++ b/src/app.js @@ -20,6 +20,7 @@ const api = require('pubsweet-server/src/routes/api') const index = require('pubsweet-server/src/routes/index') const healthcheck = require('./healthcheck') +const createCORSConfig = require('./corsConfig') const configureApp = app => { const models = require('@pubsweet/models') @@ -61,16 +62,8 @@ const configureApp = app => { } // Allow CORS from client if host / port is different - if (config.has('pubsweet-client.url')) { - const clientUrl = config.has('clientUrl') && config.get('clientUrl') - - app.use( - cors({ - origin: clientUrl, - credentials: true, - }), - ) - } + const CORSConfig = createCORSConfig() + app.use(cors(CORSConfig)) // Register passport authentication strategies app.use(passport.initialize()) diff --git a/src/corsConfig.js b/src/corsConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..c0823217b2435df0621a124fd713662b877881a3 --- /dev/null +++ b/src/corsConfig.js @@ -0,0 +1,14 @@ +const config = require('config') + +const createCORSConfig = () => { + if (!config.has('pubsweet-client.url')) return null + + const clientUrl = config.has('clientUrl') && config.get('clientUrl') + + return { + origin: clientUrl, + credentials: true, + } +} + +module.exports = createCORSConfig diff --git a/src/graphqlApi.js b/src/graphqlApi.js index 58ca13fe310df8fd6b1d8389fdd7441bbd462882..879fa122555e8a9413d5e9ed2315dc27dde9f143 100644 --- a/src/graphqlApi.js +++ b/src/graphqlApi.js @@ -1,6 +1,7 @@ const { graphqlUploadExpress } = require('graphql-upload') const createGraphQLServer = require('./graphqlServer') +const createCORSConfig = require('./corsConfig') const api = app => { app.use( @@ -13,7 +14,9 @@ const api = app => { app.use(graphqlUploadExpress()) const server = createGraphQLServer() - server.applyMiddleware({ app }) + const CORSConfig = createCORSConfig() + + server.applyMiddleware({ app, cors: CORSConfig }) } module.exports = api