Vuejs http拦截器失败

时间:2017-11-24 11:35:11

标签: javascript vuejs2

我正在尝试设置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)
  }
})

现在在我的组件中

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

拦截器没有console.log

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您没有正确配置拦截器,您应该使用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
    }
  })
})