Created
September 19, 2012 02:53
-
-
Save mkuklis/3747385 to your computer and use it in GitHub Desktop.
CORS with express, redis as session store and zepto
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
// server | |
// redis client | |
var redisClient = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST); | |
redisClient.auth(process.env.REDIS_PASS); | |
// redis session store | |
var session = { | |
secret: 'your_secret', | |
store: new RedisStore({ client: redisClient }) | |
}; | |
// CORS middleware | |
var allowCrossDomain = function(req, res, next) { | |
// TODO add origin whitelist... | |
res.header('Access-Control-Allow-Credentials', true); | |
res.header('Access-Control-Allow-Origin', req.headers.origin); | |
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); | |
res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'); | |
next(); | |
}; | |
var sessionMiddleware = express.session(session); | |
var sessionProxy = function(req, res, next) { | |
// skip session middleware in case of OPTIONS request | |
// otherwise new sessionID will be generated | |
if (req.method != "OPTIONS") { | |
return sessionMiddleware(req, res, next); | |
} | |
next(); | |
}; | |
// configure express | |
app.configure(function () { | |
app.use(express.cookieParser()); | |
app.use(express.logger('dev')); | |
app.use(express.methodOverride()); | |
app.use(allowCrossDomain); | |
app.use(sessionProxy); | |
}); | |
// client with zepto | |
// CORS needs withCredentials option set to true | |
// http://www.html5rocks.com/en/tutorials/cors/ | |
$(document).on('ajaxSend', function (e, xhr, settings){ | |
if (settings.crossDomain) { | |
xhr.withCredentials = true; | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment