首页 文章

Angular 7 / Express Session不会持续存在

提问于
浏览
0

我有一个连接到Express API后端的Angular 7应用程序,会话似乎没有持续 .

在Express中我有以下 endpoints :

router.get('/getsession', function(req, res) {
    console.log(`Session ID: ${req.session.id}`);
    res.status(200).json({ sessionid: req.session.id });
});

以下是连续两次运行 /getsession 的输出示例:

会话ID:NMi8AXhX1wf9xui0WDFwENZ_3QON_iYN会话ID:pNWcPTeJVlC8rKySw6ty5xSPa9sSME8x

我为Express启用了Credentials标头,因此它会接受它:

const cors = require("cors"); 
app.use(cors({
  credentials: true,
}));

我还为 Angular HttpClient 启用了 withCredentials ,以便它将发送cookie以及POST请求:

API_URL: string = "http://localdev.com:4200/api";
options = {
  headers: new HttpHeaders({
    'Content-Type' : 'application/json',
    'Cache-Control': 'no-cache',
    'Credentials': 'same-origin'
  }),
  withCredentials: true,
}

getSessionInfo() {
  return this.http.get(`${this.API_URL}/users/getsession`, { withCredentials: true })
  .pipe(
    catchError(this.handleError)
  )
}

localhost:4200localhost:4044 有一个Angular代理,因此可以处理API请求 .

任何帮助将不胜感激,在此先感谢:)

编辑:有趣的是,cookie正在正确传递到Express,但它仍然为每个请求创建一个新会话 . 以下是调用 /getsession endpoints 时 req.session 的结果 .

{'if-none-match':'W /“b8-afvqPuftgTLN3Wn5o / ZQx8jUsv0”',cookie:'_ga = GA1.2.1851469997.1544357368; _gid = GA1.2.1246771476.1544357368; _gat_gtag_UA_99682244_1 = 1','accept-language':'en-US,en; q = 0.9,bg; q = 0.8,mt; q = 0.7','accept-encoding':'gzip,deflate',referer:' http://localdev.com:4200/user/register','user-agent':'Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 71.0.3578.80 Safari / 537.36',接受:'application / json,text / plain,/',connection:'close',host:'localdev.com:4044'}会话ID:XWKGlJPrzYeRBU3Hi7RIAaWpowGU6Fuz {'if-none-match':'W /“ b8-mMGAHD1Tmbv1r5T YChLkQoq988“',cookie:'_ga = GA1.2.1851469997.1544357368; _gid = GA1.2.1246771476.1544357368; _gat_gtag_UA_99682244_1 = 1','accept-language':'en-US,en; q = 0.9,bg; q = 0.8,mt; q = 0.7','accept-encoding':'gzip,deflate',referer:' http://localdev.com:4200/user/register','user-agent':'Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 71.0.3578.80 Safari / 537.36',接受:'application / json,text / plain,/',connection:'close',host:'localdev.com:4044'}会话ID:T4SnSqGfo9lOWGpiyPQS0LLJgXsRnZ4T

1 回答

  • 0

    弄清楚了 . 在没有和SSL证书的开发环境中运行时,cookie将通过上述配置正确发送,但是您还需要将cookie安全设置为 false 以便将其使用 .

    它是通过以下方式实现的:

    let sessionMiddleware = session({
        secret: 'mysecret',
        saveUninitialized: true,
        resave: true,
        cookie: { secure: false },
        store: new MemcachedStore({
            hosts: ['127.0.0.1:11211'],
        })
    });
    

相关问题