Javascript Vue.js 拦截器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37228087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:03:25  来源:igfitidea点击:

Vue.js interceptor

javascriptlaravel-5.2vue.jslaravel-elixir

提问by Jamie

How can I use a interceptorin vue.js? So before every request/response it should first go to the interceptor. I already searched a lot but can't find a good documentation about that.

我如何使用interceptorin vue.js?所以在每个请求/响应之前,它应该首先转到拦截器。我已经搜索了很多,但找不到关于它的好文档。

I would like to use JWTAuth like this:

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

But I don't know how to intercept before every request/response. (I use Laravel 5.2).

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

回答by lukpep

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;
  }

});

requestis for outcoming traffic and responseif for incoming messages

request用于传出流量和response传入消息

local config in vue component is also possible.

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

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

编辑 - 由于 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');
    }
  });
});

回答by Linus Borg

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

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

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

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