Tuesday, 13 August 2013

Express sessions with AngularJS

Express sessions with AngularJS

I am trying to create a simple login using express and angularjs. The
angular js app runs on a separate server (grunt server localhost:9000)
while the express app runs on another port. For my express app, I have the
following headers set:
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:9000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
I am running angular 1.0.7, meaning that I can set some defaults in the
config step:
// Add COR ability
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
And the withCredentials on the $http request:
$http({
method : "GET",
withCredentials : true,
url : apiEndpoint + '/session'
}, success);
So after logging in with my app, a session is created and a cookie can be
seen in the response. Using chrome debugging tools, I can see that the
connect session cookie is being sent with the next subsequent request (the
session call above). On the server, however, the req.session property is
still empty. Of course I could just host the angular app with express and
get around all of this, but I'd rather keep the two projects/servers
separate.
This is a view of the /session request, with the connect session cookie
attached to the request:

No comments:

Post a Comment