我有一个连接到Express API后端的Angular 7应用,会话似乎没有持续。
在Express中,我具有以下端点:
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,
}));
我还为withCredentials
启用了Angular HttpClient
,以便它将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:4200
到localhost:4044
有一个Angular代理,因此可以处理API请求。
任何帮助将不胜感激,在此先感谢:)
编辑:有趣的是,cookie被正确地传递到Express上,但是它仍在为每个请求创建一个新会话。以下是req.session
调用/getsession
端点时的结果。
{'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':'zh-CN,en; q = 0.9,bg; q = 0.8,mt; q = 0.7',
'accept-encoding':'gzip,deflate',
引荐来源:“ http://localdev.com:4200/user/register”,
'user-agent':'Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,like Gecko)Chrome / 71.0.3578.80 Safari / 537.36',
接受:“ application / json,text / plain, / ”,
连接:“关闭”,
主机:'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':'zh-CN,en; q = 0.9,bg; q = 0.8,mt; q = 0.7',
'accept-encoding':'gzip,deflate',
引荐来源:“ http://localdev.com:4200/user/register”,
'user-agent':'Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,like Gecko)Chrome / 71.0.3578.80 Safari / 537.36',
接受:“ application / json,text / plain, / ”,
连接:“关闭”,
主机:'localdev.com:4044'}
会话ID:T4SnSqGfo9lOWGpiyPQS0LLJgXsRnZ4T
答案 0 :(得分:0)
弄清楚了。在没有SSL证书且没有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'],
})
});