Axios 不传递请求标头

Gus*_*ias 5 javascript api node.js vue.js axios

我正在构建一个 VueJS 应用程序,并使用 JSON Web 令牌作为我的身份验证系统。当我登录用户时,我将令牌存储在 localStorage 中并且工作正常。我检查了标头,它位于“授权”参数中。

我通过axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')

我看到标题了,没问题。但是,当我在 API 中对受保护的路由执行 get 请求时,返回“未经授权”。但是当我在请求中手动传递带有令牌的标头时,工作正常。

有人知道如何在执行某些请求时自动传递标头吗?

Yer*_*iaz 4

您可以使用配置对象axios.create(包括标头)创建新的 axios 实例。该配置将用于您使用该实例进行的每个后续调用。

这样的事情对我有用:

var App = Vue.component('app', {
  mounted () {
    this.response = null
    this.axiosInstance = axios.create({
      baseURL: 'http://localhost:5000/',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      }
    })
  },
  data () {
    return {
      response: this.response,
    }
  },
  methods: {
    login () {
      this.axiosInstance.post('login', {username: 'test', password: 'test'})
        .then(resp => {
          this.accessToken = resp.data.access_token
          this.axiosInstance.defaults.headers['Authorization'] = 'Bearer ' + this.accessToken
        })
        .catch(err => this.response = err.response.status + ' ' + err.response.statusText)
    },
    protected () {
      this.axiosInstance.get('protected')
        .then(resp => this.response = resp.data)
        .catch(err => this.response = err.response.status + ' ' + err.response.statusText)
    }
  },
  template: '<div><button @click="login">Connect</button><button @click="protected">Protected</button></div>'
})
Run Code Online (Sandbox Code Playgroud)