【问题标题】:Axios JWT doesn't sendAxios JWT 不发送
【发布时间】:2020-08-24 17:31:02
【问题描述】:

我有一个项目分为两层。后端使用 Spring Boot 开发,由 Sprint security 和 JWT 保护,前端使用 Vue.js 开发,使用 Axios 库进行层间通信。

我正确接收到“Bearer token”身份验证,并且所有身份验证过程都正确完成。当我尝试发送带有令牌标头的请求以访问内容但令牌未发送时出现此问题,并且 Spring 引导返回 null 而没有内容。

这里是代码

getOffers: function () {
    if (localStorage.getItem("userSession")) {
      this.aux = JSON.parse(localStorage.getItem("userSession"));
      this.token = this.aux.token;
      this.tokenHeader = "Bearer "+this.token;
      alert(this.tokenHeader)
    };
    console.log(`Bearer ${this.token}`)
    axios.
    get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
            .then(response => {
              console.log(response);
              this.offers = response.data
            }).catch(e => console.log(e))
  }

P.S:当我在 Postman 中发出请求时,它可以正常工作并返回所需的对象。这是一个邮递员的例子: postman

【问题讨论】:

标签: spring-boot vue.js axios jwt


【解决方案1】:

将 Bearer Token 注册为 Axios 的公共标头,以便所有传出的 HTTP 请求自动附加它。

window.axios = require('axios')
let bearer = window.localStorage['auth_token']

if (bearer) {`enter code here`
    window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}

并且不需要在每个请求上发送不记名令牌。

【讨论】:

    【解决方案2】:

    传递标题的正确方法是:

    axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
    

    在你的情况下试试这个:

    axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
    

    另外,检查控制台是否给出正确的Bearer 令牌:

    console.log(`Bearer ${this.token}`)
    

    【讨论】:

    • 还是不行。我尝试了axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : Bearer ${this.token}} }),但仍然不发送令牌。 console.log 返回我Bearer {token}
    • 它有什么作用? - console.log(Bearer ${this.token})
    • 特别是它返回给我Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJxd2VydHkiLCJleHAiOjE1ODkwNjIzNDEsImlhdCI6MTU4OTA0NDM0MX0.6S4V4XUB2sy2gzMx7Moh8yIcDlGQ8-xiuO8za6bkHHJim2H0tYGA268fULHMYO7pqipr3ikbK-ka-1k-ezXUAg我在 Postman 中尝试过,它工作正常
    • 可能是单引号造成问题,试试 - Authorization : this.tokenHeader 没有任何单引号。
    • { headers:{Authorization : this.tokenHeader}} 还没有。 Test 邮递员
    猜你喜欢
    • 2019-10-19
    • 2020-03-28
    • 2021-08-18
    • 2019-01-29
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多