【问题标题】:Sails session not saved in browserSails 会话未保存在浏览器中
【发布时间】:2017-06-17 15:38:13
【问题描述】:

我有一个以 Sails(0.12.13,节点 v7.2.0)作为 api 端点的启动项目。我有一个非常简单的 UserController 包含 2 个动作:

me: function(req, res)
{   
    console.log(req.session.authenticated,req.session.userId);
},

autologin: function(req, res)
{   
    req.session.authenticated = true;
    req.session.userId = 18;

    return res.ok('login_ok');
}

这是我的路由配置文件

'GET /me': 'UserController.me',
'PUT /autologin': 'UserController.autologin'

当我使用邮递员拨打/autologin 然后/me 一切正常。另一方面,当我在前端对 jquery 执行相同操作时,/autologin 之后的 /me 调用无法检索会话,因为控制台显示 undefined undefined 就像未保存会话一样。

前端代码示例:

loginInSails: function(code)
{
    $.ajax({
        type: 'PUT',
        url: sailsServerUrl + '/autologin'
    })
    .fail(function(a) 
    {  
        console.log(a);
    })
    .done(function(d)
    {
        $.ajax({
            type: 'GET',
            url: sailsServerUrl + '/me'
        })
        .fail(function(a) 
        {  
            console.log(a);
        })
        .done(function(d)
        {
            console.log(d);
        });
    });
}

我不是第一次使用 Sails,从未见过。如果您需要有关环境的更多详细信息,请询问,我会提供。

【问题讨论】:

  • 我也有类似的问题,不过,我的问题只发生在 firefox 上。

标签: node.js session sails.js


【解决方案1】:

请试试这个。

在每个请求上添加。

withCredentials: true

角度 1:

$http({
    url: serviceURL,
    method: method,
    withCredentials: true,
    params: q
}) 

jquery:

xhrFields: {
   withCredentials: true
}

loginInSails: function(code)
{
    $.ajax({
        type: 'PUT',
        url: sailsServerUrl + '/autologin',
        xhrFields: {
           withCredentials: true
        }
    })
    .fail(function(a) 
    {  
        console.log(a);
    })
    .done(function(d)
    {
        $.ajax({
            type: 'GET',
            url: sailsServerUrl + '/me',
            xhrFields: {
                withCredentials: true
            }
        })
        .fail(function(a) 
        {  
            console.log(a);
        })
        .done(function(d)
        {
            console.log(d);
        });
    });
}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2022-08-21
    • 1970-01-01
    • 2020-12-03
    • 2016-07-27
    • 2014-09-07
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多