[英]Override post requests
我有這個代碼放在我的控制台中:
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
添加一個alert()
或console.log()
以檢查它是否真的有效。 有一種方法可以悄悄地防止這種修改。
正如其他人所指出的,如果this.realSend
您是如何創建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
值簡單地調用它。 這似乎是一個更清晰的實現,與其他代碼發生沖突的可能性更小。
有關工作示例,請參閱此代碼和框。
你可以試試這個。
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function(body) { // modifies inputted request newBody = JSON.parse(body); newBody.points = 417; // sends modified request this.realSend(JSON.stringify(newBody)); }
如果您的函數沒有被調用,則可能的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.