用于身份验证标头的 vue-resource 拦截器 [英] vue-resource interceptor for auth headers
问题描述
我正在尝试设置一个 Vuejs 前端应用程序(vue-cli webpack 模板)以位于我的 Laravel API 之上.
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.
我可以通过提供正确的身份验证令牌从带有 vue-resource 的 API 获得成功响应,例如:
I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:
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
});
},
但是,我现在正在尝试设置拦截器,以便为每个请求自动添加用户的身份验证令牌.
However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.
基于 vue-resource 自述文件,我正在我的 main.js
中尝试这个:
Based on the vue-resource readme I am trying this in my main.js
:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
然后回到我现在只有的组件:
And then back in my component I now just have:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
问题:
当我在 get
本身中指定标头时,我得到一个成功的响应,但是当我通过 interceptor
传递它们时,我得到一个 401 Unauthorized
来自服务器.如何在使用拦截器时解决此问题以成功响应?
When I specify the headers in the get
itself, I get a successful response, but when I pass them through the interceptor
I get back a 401 Unauthorized
from the server. How can I fix this to respond successfully while using the interceptor?
当我使用开发工具查看传出请求时,我看到以下行为:
When I use dev-tools to view the outgoing requests I see the following behavior:
在通过向 $http.get
提供标头来发出请求时,我先发出一个成功的 OPTIONS
请求,然后发出一个成功的 GET
请求将 Authentication
标头提供给 GET
请求.
When making the request by supplying the headers to $http.get
, I make a successful OPTIONS
request and then a successful GET
request with the Authentication
header being supplied to the GET
request.
但是,当我直接从 $http.get
中删除标头并将它们移动到拦截器时,我只发出一个 GET
请求和 GET
不包含 Authentication
标头,因此它作为 401 Unauthorized
返回.
However, when I remove the headers from the $http.get
directly and move them to the interceptor, I only make a GET
request and the GET
does not contain the Authentication
header, thus it comes back as a 401 Unauthorized
.
推荐答案
原来我的问题是我在拦截器中设置标题的语法.
It turns out my problem was the syntax for which I was setting the headers in the interceptor.
应该是这样的:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
当我这样做时:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
这篇关于用于身份验证标头的 vue-resource 拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!