2016-05-14 195 views
2

如何在vue.js中使用interceptor?所以在每个请求/响应之前,它应该首先进入拦截器。我已经搜索了很多,但无法找到一个很好的文档。Vue.js拦截器

我想用JWTAuth这样的:

(function (define) { 
    'use strict' 

    define(function (require) { 

    var interceptor 

    interceptor = require('rest/interceptor') 

    /** 
    * Authenticates the request using JWT Authentication 
    * 
    * @param {Client} [client] client to wrap 
    * @param {Object} config 
    * 
    * @returns {Client} 
    */ 
    return interceptor({ 
     request: function (request, config) { 
     var token, headers 

     token = localStorage.getItem('jwt-token') 
     headers = request.headers || (request.headers = {}) 

     if (token !== null && token !== 'undefined') { 
      headers.Authorization = token 
     } 

     return request 
     }, 
     response: function (response) { 
     if (response.status && response.status.code === 401) { 
      localStorage.removeItem('jwt-token') 
     } 
     if (response.headers && response.headers.Authorization) { 
      localStorage.setItem('jwt-token', response.headers.Authorization) 
     } 
     if (response.entity && response.entity.token && response.entity.token.length > 10) { 
      localStorage.setItem('jwt-token', 'Bearer ' + response.entity.token) 
     } 
     return response 
     } 
    }) 

    }) 

}(
    typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require) } 
    // Boilerplate for AMD and Node 
)) 

但我不知道如何每个请求/响应之前拦截。 (我使用Laravel 5.2)。

+0

你有没有使用VUE资源考虑? – gurghet

回答

11

例如全球配置:

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是outcoming交通和response如果传入的消息

vue组件中的本地配置也是可能的。

编辑 - 因为有语法时才改变,现在它应该是这样的:

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

值得注意的是,这个答案有点过时了,语法现在略有不同。正如Linus在他的回答中指出的那样,请查看文档:https://github.com/pagekit/vue-resource/blob/master/docs/http.md#interceptors – Stephan

+0

如果我将'vue.http.intercepters'添加到多个文件?那么代码会在http调用之前进入每个文件? –

3

Vue本身没有AJAX功能。你是在谈论插件vue-resource,还是你使用其他库来请求?

VUE资源支持具有intereceptors:https://github.com/vuejs/vue-resource/blob/master/docs/http.md(向下滚动到最后一节)

+1

您可以使用链接到部分(https://github.com/vuejs/vue-resource/blob/master/docs/http.md#interceptors)而不是滚动 – user3479125