【问题标题】:Express Session not Working for Ajax Call快速会话不适用于 Ajax 调用
【发布时间】:2017-11-03 17:44:33
【问题描述】:

当我直接从浏览器调用/test 路由时,我发现会话已经正确设置。但是当我从 ajax 调用中执行相同操作时,我发现会话没有我之前通过其他路由 /temp 添加的信息。

快速会话配置

{
    "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 作为 fetch ajax 调用:

{
    "cookie": {
        "path": "/",
        "_expires": null,
        "originalMaxAge": null,
        "httpOnly": false,
        "secure": false
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    }
}

trackingInformation 属性显然没有设置。但是如果我在第一次调用locahost:8000/temp 之后直接从浏览器localhost:8000/test 调用相同的,我在会话中设置了 trackingInformation。

{
    "cookie": {
        ...
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    },
    "trackingInformation": {
        "useCase": "card"
    }
}

【问题讨论】:

    标签: javascript node.js ajax session express


    【解决方案1】:

    答案在 ajax 调用中。默认情况下,Fetch 不会发送 cookie。您需要通过传递 credential: 'same-origin' 作为选项来启用 cookie 的发送。所以 fetch 调用应该是 -

    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
    });
    

    查看this了解更多信息。

    【讨论】:

    • 为此浪费了一个多小时,谢谢!看起来它位于文档中,只是没有突出显示 (developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials header must be sent).
    猜你喜欢
    • 2019-01-03
    • 2018-04-12
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 2016-10-03
    • 2016-07-06
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多