简体   繁体   English

Vue.js HTTP拦截器失败

[英]Vuejs http interceptors fails

I am trying to setup vuejs http interceptors but they dont work. 我正在尝试设置vuejs http拦截器,但它们不起作用。

Vue.use(VueResource)
Vue.http.options.root = 'http://127.0.0.1:8000/api' //this works

Vue.http.interceptors.push({
  request: (request) => {
    console.log("we have a request")
    return request
  },
  response: (response) => {
    console.log('we got a response', response)
    return response
  },
  error: (err) => {
    console.log('error is', err)
  }
})

Now in my components 现在在我的组件中

this.$http.get('user/profile/')

THe interceptors dont console.log 拦截器不会console.log

Where am i going wrong? 我要去哪里错了?

You don't have the interceptors configured properly, you should be pushing a function with 2 arguments request and next . 您没有正确配置拦截器,应该使用2个参数requestnext推送一个函数。

Vue.use(VueResource)
Vue.http.options.root = 'http://127.0.0.1:8000/api' //this works

Vue.http.interceptors.push(function (request, next) {
  console.log(request)
  request.headers.set('Authorization', 'Bearer ' + sessionStorage.getItem('token'))
  next()
})

Vue.http.interceptors.push(function (request, next) {
  next(function (response) {
    console.log(response)
    if (response.status === 401) {
      // handle error or logout
      return response
    }
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM