From a1121e2e6b6026de11b1fdd7149ac53b9fe7f4ba Mon Sep 17 00:00:00 2001 From: Andrew Nicolaou Date: Thu, 23 Mar 2017 19:53:16 +0100 Subject: [PATCH] Enable CORS for all origins and requests on API (#324) * Enable CORS for all origins and requests on API * Whitelist CORS origins: *.p5js.org in production and also localhost in development --- package.json | 3 ++- server/server.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 399774cc..2f346928 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "codemirror": "^5.21.0", "connect-mongo": "^1.2.0", "cookie-parser": "^1.4.1", + "cors": "^2.8.1", "csslint": "^0.10.0", "dotenv": "^2.0.0", "dropzone": "^4.3.0", @@ -91,8 +92,8 @@ "passport": "^0.3.2", "passport-github": "^1.1.0", "passport-local": "^1.0.0", - "q": "^1.4.1", "project-name-generator": "^2.1.3", + "q": "^1.4.1", "react": "^15.1.0", "react-dom": "^15.1.0", "react-inlinesvg": "^0.4.2", diff --git a/server/server.js b/server/server.js index af8a55ae..07931c0d 100644 --- a/server/server.js +++ b/server/server.js @@ -2,6 +2,7 @@ import Express from 'express'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; +import cors from 'cors'; import session from 'express-session'; import connectMongo from 'connect-mongo'; import passport from 'passport'; @@ -29,13 +30,28 @@ import { get404Sketch } from './views/404Page'; const app = new Express(); const MongoStore = connectMongo(session); +const corsOriginsWhitelist = [ + /p5js\.org$/, +]; + // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); + + corsOriginsWhitelist.push(/localhost/); } +// Enable Cross-Origin Resource Sharing (CORS) for all origins +const corsMiddleware = cors({ + credentials: true, + origin: corsOriginsWhitelist, +}); +app.use(corsMiddleware); +// Enable pre-flight OPTIONS route for all end-points +app.options('*', corsMiddleware); + // Body parser, cookie parser, sessions, serve public assets app.use(Express.static(path.resolve(__dirname, '../static')));