【问题标题】:Modify headers of only POST XMLHttpRequest仅修改 POST XMLHttpRequest 的 headers
【发布时间】:2020-09-24 17:46:20
【问题描述】:

 (function() {
      var send = XMLHttpRequest.prototype.send,
          token = document.getElementsByTagName('meta')['csrf-token'].content;
      XMLHttpRequest.prototype.send = function(data) {
          this.setRequestHeader('X-CSRF-Token', token);
          return send.apply(this, arguments);
      };
  }());
我正在拦截所有将 X-CSRF-Token 附加到请求标头的调用。有没有办法将其限制为仅发布电话?不能使用 jQuery.ajaxPrefilter() 因为它不会拦截我想要的所有调用。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我找不到检测用于 AJAX 调用的方法的方法,但您可以尝试:

    • 重写 open 方法以验证调用使用的方法
    • 为令牌添加自定义属性
    • 在 send 方法上,评估该属性是否添加标头
    (function() {
        var proxied = window.XMLHttpRequest.prototype.open;
        window.XMLHttpRequest.prototype.open = function() {
            this.token = (arguments[0].toUpperCase() == 'POST')
                ? document.getElementsByTagName('meta')['csrf-token'].content
                : null;
            return proxied.apply(this, [].slice.call(arguments));
        };
        var send = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function(data) {
            if(this.token) {
                this.setRequestHeader('X-CSRF-Token', token);
            }
            return send.apply(this, arguments);
        };
    })();
    

    我使用this answer 来覆盖open 方法。

    严格模式中,this.token = ... 可能会失败。如果是您的情况,请使用:

            let token = (arguments[0].toUpperCase() == 'POST')
                ? document.getElementsByTagName('meta')['csrf-token'].content
                : null;
            Object.defineProperty(this, 'token', token);
    

    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

    【讨论】:

    • 谢谢!有效。只需将 toUpperCaseto 更改为 toUpperCase() 并根据我的需要修改代码。
    【解决方案2】:

    修改本机方法对我来说不合适。
    我宁愿创建一些助手来处理请求。

    例如:

    // base helper that will be used for any type of requests (POST/GET/PUT/DELETE).
    
    function makeRequest(url, settings) {
      // do what ever you need here to setup a XMLHttpRequest
    }
    
    function makePostRequest(url, body) {
        makeRequest(
            example.com, 
            { 
                body, 
                headers: { 'X-CSRF-Token': token } 
            }
        );
    }
    
    function makeGetRequest() {...}
    
    function makePostRequest() {...}
    
    function makeDeleteRequest() {...}
    

    因此,您将拥有处理请求的有用助手,并且您无需修改​​ XMLHttpRequest 原型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2013-06-02
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多