【问题标题】:JWT authentication with AXIOS使用 AXIOS 进行 JWT 身份验证
【发布时间】:2023-03-27 22:49:02
【问题描述】:

使用Vue webpack模板,尝试做JWT认证。到目前为止我做了什么:

“src/auth/index.js”:

  // Send a request to the login URL and save the returned JWT
  login (creds, redirect) {
    axios.post(LOGIN_URL, creds, (data) => {
      localStorage.setItem('access_token', data.access_token)

      this.user.authenticated = true

      // Redirect to a specified route
      if (redirect) {
        router.push(redirect)
      }
    }).error((err) => {
      context.error = err
    })
  },

我从 LoginPage.vue 调用这个函数:

  methods: {
    login () {
      var credentials = {
        username: this.credentials.username,
        password: this.credentials.password
      }
      // We need to pass the component's this context
      // to properly make use of http in the auth service
      auth.login(this, credentials, 'requests')
    }
  }

当我提交表单时,数据已提交,但我在控制台中收到以下错误:

TypeError: __WEBPACK_IMPORTED_MODULE_1_axios___default.a.post(...).error is not a function

JWT 令牌也没有保存在我的本地存储中,我做错了什么?

【问题讨论】:

  • 为什么你在发布后使​​用错误?你在哪里找到的?
  • 试试 .catch(function (error) { // 处理错误 console.log(error); })

标签: authentication vue.js jwt axios


【解决方案1】:

重写登录功能:

  login (context, creds, redirect) {
    axios.post(LOGIN_URL, creds)
      .then((response) => {
        localStorage.setItem('access_token', response.data.access_token)

        this.user.authenticated = true

        if (redirect) {
          router.push(redirect)
        }
      }).catch((err) => {
        context.error = err.response.data
      })
  },

现在一切正常。

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 2021-05-29
    • 2017-07-30
    • 2018-06-30
    • 2018-08-03
    • 2021-02-06
    • 2022-12-03
    • 2015-06-29
    • 2018-08-29
    相关资源
    最近更新 更多