Vue拦截器无法正常工作

时间:2016-07-16 15:30:08

标签: javascript vue.js

我的Vue interceptor无效。

在我的控制台中,我收到错误:

[VueResource warn]: Invalid interceptor of type object, must be a function

我的 main.js

import Vue from 'vue';
import NProgress from 'nprogress';
import Resource from 'vue-resource';
import Router from 'vue-router';
import App from './components/App.vue';
import LoginView from './components/LoginView.vue'

Vue.use(Router);
Vue.use(Resource);

var router = new Router({
    history: true
});

router.map({
    '/': {
        name: 'login',
        component: LoginView
    }
});

router.redirect({
    '*': '/'
});

Vue.http.interceptors.push({

  request (request) {
    NProgress.start();

    const token = auth.getToken();
    request.headers['Authorization'] = 'Bearer ' + token;

    request.headers['X-CSRF-TOKEN'] = document.querySelector('meta[name="token"]').content;

    return request;
  },

  response (response) {
    NProgress.done();

    if (response.status == 404) {
      router.go('/');
    } else if (response.status == 401 && response.data.refreshed_token) {
      // If you received 401 "Unauthorized" response
      // with a refreshed_token in the payload,
      // this means you've got to refresh your token
      auth.setToken(response.data.refreshed_token);
    }

    return response;
  }
});


router.start(App, 'app');

为什么我的拦截器不工作?!

1 个答案:

答案 0 :(得分:2)

您使用的是旧API,它在最新版本中已更改。

https://github.com/vuejs/vue-resource/blob/master/docs/http.md#interceptors