繁体   English   中英

Vue.js拦截器

[英]Vue.js interceptor

如何在vue.js使用interceptor 因此,在每个请求/响应之前,它应首先进入拦截器。 我已经搜索了很多但是找不到关于它的好文档。

我想像这样使用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)。

全局配置的示例:

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用于输出流量和response

也可以在vue组件中进行本地配置。

编辑 - 因为sytax现在已经改变了,它应该是这样的:

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本身没有AJAX功能。 您是在谈论插件vue-resource,还是使用其他库来请求?

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

暂无
暂无

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

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