Vue.js interceptor

戏子无情 提交于 2019-12-03 13:31:12

example for global config:

Vue.http.interceptors.push({

  request: function (request){
    request.headers['Authorization'] = auth.getAuthHeader()
    return request
  },

  response: function (response) {
    //console.log('status: ' + response.data)
    return response;
  }

});

request is for outcoming traffic and response if for incoming messages

local config in vue component is also possible.

EDIT - since sytax have changed now it should look like this:

Vue.http.interceptors.push((request, next)  => {
  request.headers['Authorization'] = auth.getAuthHeader()
  next((response) => {
    if(response.status == 401 ) {
      auth.logout();
      router.go('/login?unauthorized=1');
    }
  });
});

Vue itself has no AJAX functionality. Are you talking about the plugin vue-resource, or do you use some other library for requests?

vue-resource supports has intereceptors: https://github.com/vuejs/vue-resource/blob/master/docs/http.md (scroll down to the last section)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!