Created
April 7, 2018 12:36
-
-
Save rao123dk/49285791703be56d59d1f3d5172df765 to your computer and use it in GitHub Desktop.
express application to allow multiple origins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.use(function(req, res, next) { | |
var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000']; | |
var origin = req.headers.origin; | |
if(allowedOrigins.indexOf(origin) > -1){ | |
res.setHeader('Access-Control-Allow-Origin', origin); | |
} | |
//res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020'); | |
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS'); | |
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); | |
res.header('Access-Control-Allow-Credentials', true); | |
return next(); | |
}); | |
//OR Another Way | |
app.all('/*', function(req, res, next) { | |
// CORS headers | |
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain | |
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); | |
// Set custom headers for CORS | |
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); | |
if (req.method == 'OPTIONS') { | |
res.status(200).end(); | |
} else { | |
next(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment