Angular 6和Node js表示mysql会话不起作用

时间:2019-02-13 14:37:47

标签: node.js express angular6 angular-httpclient

我正在尝试将登录会话保存在express-mysql-session节点js上,但是登录成功后,该会话将无法正常工作。

这是我的角度服务:

  public httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'charset=utf-8; application/json;'
    })
  };

  login() {
    return this.http.post(this.globals.baseUrl + "/login", this.httpOptions);
  }

  loginWithParams(email: any, password: any) {
    return this.http.post(this.globals.baseUrl + "/login", { password: password, email: email }, this.httpOptions);
  }

首先,我调用带参数的登录名来创建会话,在我调用不带参数的登录名后,只是为了检查会话是否仍然有效,而在第二个调用中,会话消失了。

var storeOptionMySQL = {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: 'tracegaming', // Database name. 
    checkExpirationInterval: 2700000, // How frequently expired sessions will be cleared; milliseconds. 
    expiration: 1800000, // The maximum age of a valid session; milliseconds. 
    createDatabaseTable: true, // Whether or not to create the sessions database table, if one does not already exist. 
    schema: {
        tableName: 'sessions',
        columnNames: {
            session_id: 'session_id',
            expires: 'expires',
            data: 'data'
        }
    }
};

var sessionStore = new MySQLStore(storeOptionMySQL, function () {
    sessionStore.setExpirationInterval();
});

router.use(session({
    store: sessionStore,
    resave: true,
    saveUninitialized: false,
    secret: 'whatsup'
}));

router.post('/login', function (req, res, next) {
    console.log(req.session);//second call, do not have values
    var sessionValidatorResponse = new SessionValidator().validate(req.session);
    if (sessionValidatorResponse.status != 1) {
        if (paramsvalidator.validate('/login', req.body)) {
            var email = req.body.email;
            var password = sha1(req.body.password);
            var loginManager = new LoginManager(pool);
            loginManager.selectUserByEmail(email, password, function (result) {
                if (result.status == 1 && result.data.length > 0) {
                    req.session.userId = result.data[0].id;
                    req.session.email = email;
                    req.session.name = result.data[0].name;
                    console.log(req.session); //first call and print the correct values
                    return res.json({ status: 1, msg: 'Login success', user: { email: email, name: result.data[0].name, id: result.data[0].id } });
                } else {
                    return res.json({ status: 0, msg: 'Credenciales incorrectas' });
                }
            });
        } else {
            return res.json({ status: 0, msg: 'Wrong params, please check the documentation.' })
        }
    } else {
        return res.json({ status: 1, msg: 'Login success' });
    }
});

会话正确保存在数据库中。

节点运行在3000端口,角度运行在4200端口。

如果我使用邮递员,一切都会很好。

0 个答案:

没有答案