我正在尝试设置一个Vuejs正面应用程序(vue-cli webpack模板),以位于我的Laravel之上。
例如,通过提供正确的auth令牌,我能够通过提供正确的auth令牌从API获得一个成功的vue-资源响应:
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
});
},
但是,我现在试图设置拦截器,以便为每个请求自动添加用户的auth令牌。
基于vue资源自述,我正在我的main.js
中尝试这一点。
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
});
问题:
当我在get
本身中指定标头时,我会得到一个成功的响应,但是当我通过interceptor
传递它们时,我会从服务器得到一个401 Unauthorized
。如何在使用拦截器时修复此问题以成功响应?
编辑:当我使用开发工具查看传出请求时,我看到以下行为:
当通过向$http.get
提供标头进行请求时,我成功地发出了OPTIONS
请求,然后成功地向GET
请求提供了Authentication
头的GET
请求。
但是,当我从$http.get
中直接删除头部并将它们移动到拦截器时,我只发出一个GET
请求,而GET
不包含Authentication
头,因此它作为一个401 Unauthorized
返回。
发布于 2016-09-23 18:17:04
事实证明,我的问题是在拦截器中设置标头的语法。
应该是这样的:
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()
})
发布于 2017-07-06 07:40:05
添加此选项:
Vue.http.options.credentials = true;
并以全局方式使用拦截器:
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
});
https://stackoverflow.com/questions/39665244
复制相似问题