Express sessions with AngularJS

拜拜、爱过 提交于 2019-12-06 07:32:36

So if I get your setup right, you have:

angularjs running on grunt server <---> express server

And you want to access the session on the express server? If this is the case, then you need a way to share the session between those two servers. I would recommend using the redis-connect module (there is also express-mongodb). It stores the session object in a redis database which can be accessed from both servers. I've never used the grunt server before, but I've done this using two express servers. MemoryStore wont work here, because you have two seperate processes which won't share the same memory.

I had to mess around with a few different things to get this working. First, I upgraded to the edge angular, as some values could not be globally defaulted on $http that I needed.

In the angular config() step, I added:

// Add COR ability
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

In express, I created an angular middleware:

exports.angularHeaders = function(req, res, next){
    res.header("Access-Control-Allow-Origin", '{{insert your ui endpoint}}');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Credentials", "true");
    next();
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!