我正在try 设置一个Vuejs前端应用程序(vue cli网页包模板),使其位于我的Larvel API之上.
通过提供正确的身份验证令牌,我可以通过vue资源从API获得成功响应,例如:
methods: {
getUser () {
this.$http.get('http://localhost:8000/api/user',
{
headers: {
'Authorization': 'Bearer eyJ0e.....etc',
'Accept': 'application/json'
}
}).then((response) => {
this.name = response.data.name
});
},
然而,我现在正在try 设置拦截器,以便 for each 请求自动添加用户的身份验证令牌.
基于vue资源自述,我将在我的main.js
页中try 这一点:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
然后回到我的组件中,我现在有:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Problem:
当我在get
本身中指定头时,我得到了一个成功的响应,但当我将它们传递到interceptor
时,我从服务器返回了401 Unauthorized
.如何在使用拦截器时修复此问题以成功响应?
Edit:
当通过向$http.get
提供报头来发出请求时,我发出了一个成功的OPTIONS
请求,然后是一个成功的GET
请求,其中Authentication
报头被提供给了GET
请求.
然而,当我直接从$http.get
中删除头并将其移动到拦截器时,我只发出GET
请求,而GET
不包含Authentication
头,因此返回为401 Unauthorized
.