覆盖post请求



我将下面的代码放入我的控制台:

XMLHttpRequest.prototype.send = function(body) {
// modifies inputted request
newBody = JSON.parse(body);
newBody.points = 417;
// sends modified request
this.realSend(JSON.stringify(newBody));
}

每次发送请求时,它都应该得到417分,但是当我查看请求体时,它仍然表示原始点数。任何帮助吗?

尝试将alert()console.log()添加到修改的XMLHttpRequest.prototype.send中,以检查它是否实际工作。有一种方法可以静默地防止这种修改。

如果您的函数没有被调用,可能使用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);
}

正如其他人所指出的,如果不查看如何创建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值调用它。这似乎是一个更干净的实现,与其他代码冲突的机会更少。

请参阅此代码盒以获取工作示例。

最新更新