Express会话不适用于Ajax呼叫 [英] Express Session not Working for Ajax Call
问题描述
当我直接从浏览器调用/test
路由时,我发现会话已正确设置.但是,当我通过ajax调用执行相同操作时,我发现该会话不具有我之前通过其他路由/temp
添加的信息.
When I call the /test
route directly from the browser, I find that the session has been properly set. But when I do the same from an ajax call, I find that the session does not have the information I had previously added through the other route /temp
.
express-session配置
{
"key": "nsid",
"secret": "some secret password",
"cookie": {
"path": "/",
"httpOnly": false,
"maxAge": null,
"secure": false
},
"resave": true,
"saveUninitialized": true,
"proxy": null
}
routes.js
router.get('/temp', (req, res) => {
const useCase = 'card';
req.session = req.session || {};
req.session.trackingInformation = {};
req.session.trackingInformation.useCase = useCase;
req.session.save();
console.log(req.session);
res.render('/temp');
});
router.get('/test', (req, res) => {
console.log(Util.inspect(req.session));
res.send({});
});
ajax通话
fetch('/test').then((response) => {
if (response.status >= 400) {
console.log(response.status);
}
return response.json();
}).then((json) => {
console.log(json);
//do something
});
当我调用localhost:8000/temp
然后调用/test
作为获取ajax调用时:
When I call the localhost:8000/temp
and then call the /test
as a fetch ajax call:
{
"cookie": {
"path": "/",
"_expires": null,
"originalMaxAge": null,
"httpOnly": false,
"secure": false
},
"_csrfSecret": "secret",
"_shared": {
"deviceInfo": {
...
}
}
}
trackingInformation属性显然未设置.但是,如果我在第一次调用locahost:8000/temp
之后直接从浏览器localhost:8000/test
调用相同的代码,则在会话中设置了trackingInformation.
The trackingInformation property clearly is not set. But if I call the same directly from my browser localhost:8000/test
after first calling locahost:8000/temp
, I have the trackingInformation set in the session.
{
"cookie": {
...
},
"_csrfSecret": "secret",
"_shared": {
"deviceInfo": {
...
}
},
"trackingInformation": {
"useCase": "card"
}
}
推荐答案
答案在ajax调用中.默认情况下,抓取不会发送Cookie.您需要通过传递credential: 'same-origin'
作为选项来启用cookie的发送.因此,提取调用应该是-
The answer was in the ajax call. Fetch by default doesn't send the cookies. You need to enable the sending of cookies by passing credential: 'same-origin'
as an option. So the fetch call should have been -
fetch('/test', {
credentials: 'same-origin'
}).then((response) => {
if (response.status >= 400) {
console.log(response.status);
}
return response.json();
}).then((json) => {
console.log(json);
//do something
});
请参阅此以获取更多信息.
Look at this for more information.
这篇关于Express会话不适用于Ajax呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!