用nodejs做后端,页面跳转后session中的数据消失,请问怎么解决?

小刘
  • 526

我的前端页面放在ngnix里面,端口是80

我的后台是用nodejs写的,端口是3060,

现在我在登陆页面进行登陆,请求http://www.xinlizhiyouni.com:80/user/login/phone接口,然后将数据保存到nodejs的session中,然后跳转到http://www.xinlizhiyouni.com:80/advertise/add.html请求http://www.xinlizhiyouni.com:80/user/logout接口,但是此时session数据为undefine,请问为什么我的session数据丢失了,怎么才能正确在session中保留数据,然后跳转后不丢失


//设置跨域访问
app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
   res.header("X-Powered-By",' 3.2.1');
   res.header("Content-Type", "application/json;charset=utf-8");
   next();
});

app.all('/user/login/phone', (req, res) => {
    let sess = req.session;
    let param = req.body;
    console.log('param == ', param)
    let selectParams = {
        phone: param.mobilePhoneUsername
    };
    let userModSql = "SELECT ul.password, ui.uid, ui.name, ui.sex, ui.phone FROM user_information ui, user_login ul WHERE ui.uid=ul.id AND ui.phone=?";
    pool.getConnection( (err, connection) => {
        if (err) {
            throw err;
        } else {
            connection.query(
                userModSql,
                [selectParams['phone']],
                function (err, rows) {
                    if (err) {
                        throw err;
                    } else {
                        console.log("rows === ", rows);
                        let verifySign = cryptPwd(param.mobilePhonePassword, "liu")
                        console.log("verifySign === ", verifySign);
                        if (rows[0].password === verifySign ) {
                            req.session.loginUserInfo = rows[0]
                            //设置cookie
                            res.cookie('username',rows[0], {maxAge:100000}); //有效期以毫秒为单位
                            // res.json({code: 0, message: 'success'});
                            res.redirect('http://www.xinlizhiyouni.com:80/advertise/add.html');
                        } else {
                            res.json({code: 1, message: 'fail'});
                        }
                    }
                }
            )
        }
    })
});

app.all("/user/logout", function(req, res, next) {
    console.log("loginUserInfo == ", req.session.loginUserInfo);
    res.json({ret_code: 0, ret_msg: '退出登录成功'});
});

配置session的代码

app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());

app.use(cookieParser());
app.use(session({
    secret: '123456',
    cookie: {maxAge: 60000},
    resave: false
}));

修改后的代码

let identityKey = 'superKey';

app.use(cookieParser());
app.use(session({
    name: identityKey,
    secret: 'heart',  // 用来对session id相关的cookie进行签名
    cookie: {maxAge: 60000},
    resave: false
}));

//设置跨域访问
app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
   res.header("X-Powered-By",' 3.2.1');
   res.header("Content-Type", "application/json;charset=utf-8");
   next();
});

app.all('/', function(req, res, next){
    let sess = req.session;
    let loginUser = sess.loginUser;
    let isLogined = !!loginUser;
});

// 登录接口
app.all('/test/user/login', function(req, res, next){
    let sess = req.session;
    let user = {
        "name": req.body.name
    };
    console.log("登陆接口测试");
    sess.loginUser = user.name;
    res.json({ret_code: 0, ret_msg: '登录成功'});
});

app.all('/test/user/logout', function(req, res, next){
    let sess = req.session;
    let loginUser = sess.loginUser;

    console.log("测试登出接口");
    console.log(loginUser);

});
回复
阅读 2k
2 个回答
✓ 已被采纳

经过本人的研究,发现了具体的原因

从80端口去3060端口请求数据,然后跳转到80端口后,相当于跨域获取session,所以无法再次获取session的数据

我的解决办法如下

在nginx的配置文件上进行配置,解决跨域的问题

就能正确获取到session

你知道吗?

宣传栏