【问题标题】:Override post requests覆盖发布请求
【发布时间】:2021-10-26 01:28:54
【问题描述】:

我将这段代码放在控制台中:

XMLHttpRequest.prototype.send = function(body) {
    // modifies inputted request
    newBody = JSON.parse(body);
    newBody.points = 417;

  // sends modified request
    this.realSend(JSON.stringify(newBody));
}

应该是每次发送请求都会打分417,但是当我查看请求正文时,它仍然是原来的积分数量。有什么帮助吗?

【问题讨论】:

  • 这部分看起来不错
  • 您在哪里看到您发送的请求?你是如何保存原来的 XMLHttpRequest.prototype.send 的,你以后显然会在 this.realSend(...) 中使用它?

标签: javascript http xmlhttprequest http-post


【解决方案1】:

尝试在修改后的XMLHttpRequest.prototype.send 中添加alert()console.log() 以检查它是否真的有效。有一种方法可以静默地防止这种修改。

【讨论】:

  • 警报永远不会出现,我做错了什么?也许该网站使用 fetch 代替?老实说,我不知道,因为我对所有这些请求都是新手。
  • 无法保证fetch 会得到您想要的,尽管您可以尝试一下。如果不是你的网站,那么可能会有很多不同的技巧,因为发送帖子请求的方式有很多
  • 是的,这不是我的网站。
【解决方案2】:

正如其他人所指出的,如果不查看您是如何创建 this.realSend 的,就很难准确诊断出您遇到的错误。

但是,此代码将起作用:

const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (body) {
    const newBody = JSON.parse(body);
    newBody.points = 417;
    send.call(this, JSON.stringify(newBody));
};

请注意,我没有将原始的send 方法存储在XMLHttpRequest.prototype 上,而是保存在一个单独的变量中,并通过send.call() 使用正确的this 值简单地调用它。这似乎是一个更简洁的实现,与其他代码发生冲突的可能性更小。

有关工作示例,请参阅 this codesandbox

【讨论】:

    【解决方案3】:

    如果您的函数没有被调用,可能fetch 用于发出ajax 请求。

    所以你可以像这样包装这两个函数

    const send = XMLHttpRequest.prototype.send;
    const _fetch = window.fetch;
    
    XMLHttpRequest.prototype.send = function (body) {
       const newBody = JSON.parse(body);
       newBody.points = 417;
       send.call(this, JSON.stringify(newBody));
    };
    
    window.fetch = function(url, options){
       let newBody;
       if(options.body) {
          newBody = JSON.parse(options.body);
          newBody.points = 417;
          options.body = JSON.stringify(newBody);
       }
       _fetch.call(this, url, options);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多