在客户端的静态页面和动态页面之间移动时保持快速会话

时间:2019-03-23 09:28:23

标签: node.js express vue.js express-session

我正在尝试为用户身份验证建立快速会话。 我有一个node.js后端,以及角度和静态页面前端(两个前端)。

我的节点后端在我的路由上接受用户名和密码进行身份验证 作为发帖请求http://localhost:3000/users/login

我的旅程如下:
1。向用户显示一个静态前端登录页面(该页面是通过在静态html页面上将axios注入vue.js来设计的),其中用户请求使用其凭据进行登录。客户端前端托管在http://localhost:3011/
2。应用程序现在将向http://localhost:3000/users/login发送发布请求以验证凭据。
3。如果凭据有效,则服务器将使用req.session创建一个新会话(express-session)。在此会话中,我还将存储我的令牌,该令牌用于对任何后续请求进行用户身份验证(此令牌已保存在数据库中,并已针对所有其他请求进行验证)。然后,服务器将以200 OKAY状态进行响应。
4。一旦vue应用程序获得肯定的响应,客户端会将应用程序重定向到http://localhost:3000/,我在dist文件夹中有角度应用程序。

如果在POSTMAN中我对http://localhost:3000/users/login进行了发布,然后对http://localhost:3000/进行了GET,则当服务器响应GET请求时,我可以在日志中看到令牌。
但是,如果我从vue应用程序向http://localhost:3000/users/login发送发帖请求,然后在成功通过身份验证后重定向到http://localhost:3000/,则在日志中看不到令牌。

客户端(Vue)上的代码段

submit() {
      this.errMsg = "";
      axios
        .post("http://localhost:3000/users/login", {
          user: this.user,
          password: this.password
        })
        .then(response => {
          window.location = "http://localhost:3000/";
        })
        .catch(err => {
          console.log(err);
          this.errMsg = err.data.statusText;
        });
    }

服务器端内部登录代码

router.route("/login").post((req, res) => {
  let { user, password } = req.body;
  merchant_table
    .findOne({ attributes: ["id"], where: { email, password } })
    .then(result => {
      if (result) {
        let token = 12345;
        token_table
          .create({ m_id: result.id, token })
          .then(result => {
            req.session.user = result.token;
            console.log("session is", req.session); //THIS SHOWS THE TOKEN
            res.status(200).json({status:"OKAY!"})
          });
      } else {
        res.status(401).json({status:"Invalid User!"})
      }
    })
    .catch(error => console.log(error));
});

http://localhost:3000/的请求API中的代码

app.use("/", function(req, res) {
  console.log("Session is", req.session); //THIS SHOWS THE TOKEN FOR POSTMAN, NOT WHEN WORKING WITH VUE
  res.sendFile(__dirname + "/dist/index.html");
});

由于axios发布请求和后续重定向均指向http://localhost:3000/,因此我希望令牌得以维护。但它似乎将其视为新连接。这种方法是错误的吗?有没有办法在重定向时跟踪令牌?我只需要令牌一次,因为这样我会将其存储在angular应用程序中,并根据需要发送给其他请求。 我该怎么办?

0 个答案:

没有答案