tam*_*am5 12 vue.js vue-resource
我正在尝试设置一个Vuejs前端应用程序(vue-cli webpack模板),以便放在我的Laravel API之上.
通过提供正确的身份验证令牌,我可以通过vue-resource从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
});
},
Run Code Online (Sandbox Code Playgroud)
但是,我现在正在尝试设置拦截器,以便为每个请求自动添加用户的身份验证令牌.
基于vue-resource自述文件我在我的尝试中main.js:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Run Code Online (Sandbox Code Playgroud)
然后回到我的组件我现在只有:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Run Code Online (Sandbox Code Playgroud)
问题:
当我在get自身中指定标题时,我得到了一个成功的响应,但是当我通过它时,我从服务器interceptor返回一个401 Unauthorized.我怎样才能解决这个问题,以便在使用拦截器时成功响应?
编辑: 当我使用dev-tools查看传出请求时,我看到以下行为:
通过提供标头来发出请求时$http.get,我发出了一个成功的OPTIONS请求,然后成功GET请求,并将Authentication标头提供给GET请求.
但是,当我从$http.get直接删除标题并将它们移动到拦截器时,我只发出一个GET请求并且GET不包含Authentication标题,因此它返回为a 401 Unauthorized.
tam*_*am5 31
事实证明我的问题是我在拦截器中设置标头的语法.
它应该是这样的:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
Run Code Online (Sandbox Code Playgroud)
虽然我这样做:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17722 次 |
| 最近记录: |