2017-06-21 109 views
1

我是Vuejs 2的新手,目前使用vue-resource从服务器检索数据。但是,为了从服务器检索数据,我需要同时在请求头中传递一个令牌。vue-resource没有在请求标头中传递令牌

所以问题是,我无法检索数据,因为令牌没有传递到请求头,使用vue-resource。

这里是使用VUE资源的拦截器(在令牌传递)的方法来拦截GET请求:

test() { 
    this.$http.interceptors.push((request) => { 
    var accessToken = window.localStorage.getItem('access_token') 
    request.headers.set('x-access-token', accessToken) 
    return request 
    }) 
    this.$http.get(staffUrl) 
    .then(response => { 
    console.log(response) 
    }, (response) => { 
    console.log(response) 
    }) 
} 

的文档VUE资源,HTTP:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

当我尝试获取数据,我最终出现错误403(禁止),并在开发工具中检查请求标头后,我也无法在请求标头中找到标记。

请告诉我我错了,因为我真的是新来的,所以我感谢任何帮助!谢谢!

回答

1

使用$ http在组件内设置拦截器不起作用,或者至少它不会在我的测试中。如果您在test方法中推送后立即检查/ log this.$http.interceptors,则会注意到拦截器未添加。

如果您在之前添加了拦截器,那么您将实例化您的Vue,但是拦截器会被正确添加并且该报头将被添加到请求中。

Vue.http.interceptors.push((request, next) => { 
    var accessToken = "xyxyxyx" 
    request.headers.set('x-access-token', accessToken) 
    next() 
}) 

new Vue({...}) 

这是我使用的test code

另外请注意,你应该总是调用下一个传递给拦截器的方法。

+0

嗨!谢谢你的帮助!在阅读你的解释之后,我能够做到这一点。我不知道这是否是一个好主意,但是在实例化Vue之前,我在main.js中放入了'Vue.http.interceptors',然后它工作:-) – mary

相关问题