【问题标题】:How to Intercept XMLHttpRequest and change request URL如何拦截 XMLHttpRequest 并更改请求 URL
【发布时间】:2018-10-26 08:47:34
【问题描述】:

我的前端向后端服务器发送请求。我怎样才能拦截这个请求,并重定向到另一个回来?如何改回网址?

  const intercept = (urlmatch, callback) => {
  let send = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.send = function() {
    this.addEventListener('readystatechange', function() {
      if (this.responseURL.includes(urlmatch) && this.readyState === 4) {
        callback(this);
      }
    }, false);
    send.apply(this, arguments);
  };
};

谢谢!

【问题讨论】:

  • 目的是什么?如果您可能需要另一个后端,那么最好使用可以更改的基本 url 常量构造 url。你为什么要修补send 而不是open
  • 你的意思是不改前端代码?
  • @estus 我需要创建一个拦截器,它将所有前端请求从一个后端重定向到另一个
  • @AkshayMilmile 差不多,只是添加了新功能
  • 这好像是前端代码,你是在GUI级别拦截吗?

标签: javascript node.js


【解决方案1】:

这可以通过修补XMLHttpRequestopen轻松实现:

const intercept = (urlmatch, newurl) => {
  const open = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url, ...rest) {
    url = url.replace(urlmatch, newurl);
    return open.call(this, method, url, ...rest);
  };
}

intercept('http:/example.com/', 'http:/my-example.com/');

根据本地需求修改全局变量是一种不好的做法,可能会导致无法预料的后果。

除非目标是篡改其他人的应用程序(例如,使用用户脚本),否则更简洁的方法是修改应用程序以使更改基本 url 成为可能,例如来自

makeRequest('http:/example.com/api/...')

makeRequest(BASE_API_URL + '...')

其中BASE_API_URL 是应用程序常量,可以在应用程序初始化时更改,包括环境变量、全局变量、依赖注入等。

如果应用程序使用某种包装器而不是直接使用XMLHttpRequest,则可以在包装器中实现基本 URL 功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    相关资源
    最近更新 更多