您可以使用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>'
})
有一些方法来设置这个全球与Axios公司使用? –
https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests?rq=1可能会帮助 –
你可以使用“vuex”这是中央存储系统看看这个[链接。](https://vuex.vuejs.org/en/intro.html)它的使用非常简单。 “ps:我也在使用”你可以创建getters作为axios请求,你可以访问所有的服务器端组件 –