node.js 如何使用 VueJS 保存用户会话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39798033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:36:12  来源:igfitidea点击:

How to save users sessions with VueJS?

node.jsvue.js

提问by Kevin Conklin

I am trying to figure out how to save users session when they log out. e.g. multiple shopping carts, transactions, and even previous searches. I am pretty new to the whole backend language and I am just seeking guidance on the matter. I have tried my share at google-foo for this matter, but have not found any good documentation on what I am trying to achieve.

我试图弄清楚如何在用户注销时保存用户会话。例如多个购物车、交易,甚至以前的搜索。我对整个后端语言还很陌生,我只是在寻求有关此事的指导。我已经在 google-foo 上尝试过我的分享,但没有找到任何关于我想要实现的目标的好的文档。

Can anyone help and/or guide me?

任何人都可以帮助和/或指导我吗?

回答by Dary

try use vue-session

尝试使用vue-session

example in login area:

登录区示例:

export default {
    name: 'login',
    methods: {
        login: function () {
          this.$http.post('http://somehost/user/login', {
            password: this.password,
            email: this.email
          }).then(function (response) {
            if (response.status === 200 && 'token' in response.body) {
              this.$session.start()
              this.$session.set('jwt', response.body.token)
              Vue.http.headers.common['Authorization'] = 'Bearer ' + response.body.token
              this.$router.push('/panel/search')
            }
          }, function (err) {
            console.log('err', err)
          })
        }
    }
}

logged in area:

登录区域:

export default {
  name: 'panel',
  data () {
    return { }
  },
  beforeCreate: function () {
    if (!this.$session.exists()) {
      this.$router.push('/')
    }
  },
  methods: {
    logout: function () {
      this.$session.destroy()
      this.$router.push('/')
    }
  }
}

回答by Justin MacArthur

You need to either store the session in a cookie or on the server.

您需要将会话存储在 cookie 中或服务器上。

vue-cookiewould be a good component to use for browser storage.

vue-cookie将是用于浏览器存储的一个很好的组件。

if you're storing on the server you need to create an endpoint for the data and store it in some fashion; a database, cache file, redis, etc.

如果您存储在服务器上,您需要为数据创建一个端点并以某种方式存储它;数据库、缓存文件、redis 等。