Created
April 19, 2014 18:19
-
-
Save DanisHack/11092806 to your computer and use it in GitHub Desktop.
Adding CORS support in expressjs app
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
var express = require('express') | |
, routes = require('./modules/analytics/routes') | |
, http = require('http') | |
, path = require('path'); | |
var app = express(); | |
// all environments | |
app.set('port', process.env.PORT || 3000); | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'jade'); | |
app.use(express.favicon()); | |
app.use(express.logger('dev')); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
// development only | |
if ('development' == app.get('env')) { | |
app.use(express.errorHandler()); | |
} | |
// CORS in express | |
app.all('*', function(req, res, next){ | |
if (!req.get('Origin')) return next(); | |
// use "*" here to accept any origin | |
res.set('Access-Control-Allow-Origin', 'http://localhost:4000'); // add your domain name here, to allow cross origin | |
res.set('Access-Control-Allow-Methods' | |
, 'X-Requested-With, Content-Type'); | |
// res.set('Access-Control-Allow-Max-Age', 3600); | |
if ('OPTIONS' == req.method) return res.send(200); | |
next(); | |
}); | |
http.createServer(app).listen(app.get('port'), function(){ | |
console.log('Express server listening on port ' + app.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment