2017-09-06 35 views
0

我正在构建一个VueJS应用程序,我使用JSON网络令牌作为我的身份验证系统。当我登录用户时,我用localStorage存储了令牌并且工作正常。我检查标题,它在'授权'参数中。Axios没有通过请求传递头文件

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

我看见头和它没关系。但是,当我在我的API中对受保护的路由执行get请求时,返回'未授权'。但是当我在请求中手动传递带有标记的标头时,工作正常。

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

回答

0

您可以使用axios.create创建一个包含标头的config object的新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>' 
}) 
0

试试这个..

//in get request 
const auth = { 
     headers: {Authorization:'JWT ' + localStorage.getItem('token')} 
    } 

axios.get('http://yourapi.com',auth).then(result => { 
console.log(result.data) 
}) 

//in post request 
const auth = { 
     headers: {Authorization:'JWT ' + localStorage.getItem('token')} 
    } 
//note:auth will be 3rd parameter in post request 
axios.post('http://yourapi.com',{somekey:'some value'},auth).then(result => { 
console.log(result.data) 
}) 
+0

有一些方法来设置这个全球与Axios公司使用? –

+0

https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests?rq=1可能会帮助 –

+0

你可以使用“vuex”这是中央存储系统看看这个[链接。](https://vuex.vuejs.org/en/intro.html)它的使用非常简单。 “ps:我也在使用”你可以创建getters作为axios请求,你可以访问所有的服务器端组件 –