Skip to content

Commit a1121e2

Browse files
andrewncatarak
authored andcommitted
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
1 parent fe6acc9 commit a1121e2

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
"codemirror": "^5.21.0",
7070
"connect-mongo": "^1.2.0",
7171
"cookie-parser": "^1.4.1",
72+
"cors": "^2.8.1",
7273
"csslint": "^0.10.0",
7374
"dotenv": "^2.0.0",
7475
"dropzone": "^4.3.0",
@@ -91,8 +92,8 @@
9192
"passport": "^0.3.2",
9293
"passport-github": "^1.1.0",
9394
"passport-local": "^1.0.0",
94-
"q": "^1.4.1",
9595
"project-name-generator": "^2.1.3",
96+
"q": "^1.4.1",
9697
"react": "^15.1.0",
9798
"react-dom": "^15.1.0",
9899
"react-inlinesvg": "^0.4.2",

server/server.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import Express from 'express';
22
import mongoose from 'mongoose';
33
import bodyParser from 'body-parser';
44
import cookieParser from 'cookie-parser';
5+
import cors from 'cors';
56
import session from 'express-session';
67
import connectMongo from 'connect-mongo';
78
import passport from 'passport';
@@ -29,13 +30,28 @@ import { get404Sketch } from './views/404Page';
2930
const app = new Express();
3031
const MongoStore = connectMongo(session);
3132

33+
const corsOriginsWhitelist = [
34+
/p5js\.org$/,
35+
];
36+
3237
// Run Webpack dev server in development mode
3338
if (process.env.NODE_ENV === 'development') {
3439
const compiler = webpack(config);
3540
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
3641
app.use(webpackHotMiddleware(compiler));
42+
43+
corsOriginsWhitelist.push(/localhost/);
3744
}
3845

46+
// Enable Cross-Origin Resource Sharing (CORS) for all origins
47+
const corsMiddleware = cors({
48+
credentials: true,
49+
origin: corsOriginsWhitelist,
50+
});
51+
app.use(corsMiddleware);
52+
// Enable pre-flight OPTIONS route for all end-points
53+
app.options('*', corsMiddleware);
54+
3955
// Body parser, cookie parser, sessions, serve public assets
4056

4157
app.use(Express.static(path.resolve(__dirname, '../static')));

0 commit comments

Comments
 (0)