如果后端和前端分别部署在 Heroku 中,则从 express 应用程序访问 req.session 到 angular (typescript)

Accessing req.session from express app to angular (typescript) if the backend and frontend was deployed separately in Heroku

I'm trying to access the req.session from my express app to angular (backend and frontend deployed separately in heroku). I already set up the CORS to handle http request from angular to my express app.

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json,X-XSRF-TOKEN,CSRF-Token,X-CSRF-Token');
next();
});

我在处理或获取请求时遇到问题 session,因为它始终是空的。在进行 http get 时,我能够将 connect.sid 发送到我的 express 应用程序,但在 angular 中发出另一个请求时它不会持续存在,因此每次我刷新 angular 应用程序 session ID也会被刷新。我需要 cookie 持久保存,这样我就可以在发出 post 请求时使用它(即向 angular、"Response will be csrf token" 发出一个 http get 请求,然后使用另一个 http post 请求用于登录的请求的 csrf 令牌,但由于每个 session id 在每个请求中都会不同,因此 csrf 令牌将无效。每个 express sessions 都存储在 mongo lab through connect-mongo npm 模块。

app.use(session({
    secret : process.env.sessionKey,    
    httpOnly: true,
    resave : true,
    saveUninitialized: true, 
    store  : new mongoStore({ mongooseConnection: mongoose.connection }),
    cookie : { maxAge: 60 * 60 * 1000}
}));

我的 Angular 应用程序中的 Http get post 已经运行,因此 CORS 设置正确。当我在 angular 中访问路由 url (login) 检查响应 header 时,这将使 Http get 请求调用我注意到cookies (cookies.sid) 是在 header 上设置的,但我不知道如何存储它,所以我可以在 angular 应用程序中为我的下一个请求使用这个 cookies session ID (如post登录)

如果您想读取保存在浏览器中的 cookie,您可以在任何需要的地方创建以下函数:

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return null;
}

要检查 cookie name,请转到浏览器开发人员控制台中的 Application 选项卡,我猜在这种情况下 connect.sid。获取名称并调用

getCookie(<cookie-name>); you can use this value further.