How to Intercept XMLHttpRequest and change request URL

落花浮王杯 提交于 2021-02-08 10:17:34

问题


My front send requests to the back server. How can I intercept this request, and redirect to another back? How can I change back's URL?

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

Thanks!


回答1:


This can be easily achieved by patching XMLHttpRequest open:

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/');

Modifying globals for local needs is a bad practice that may lead to unforseen consequences.

Unless the goal is to tamper somebody else's application (for instance, with user script), a cleaner way is to modify the application to make it possible to change base url, e.g. from

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

to

makeRequest(BASE_API_URL + '...')

Where BASE_API_URL is application constant that can be changed on application initialization, with environment variables, globals, dependency injection, etc.

If an application uses some kind of a wrapper instead of XMLHttpRequest directly, base URL functionality may be implemented in a wrapper.



来源:https://stackoverflow.com/questions/53004906/how-to-intercept-xmlhttprequest-and-change-request-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!