如何将两个fetch返回数据存为变量对比且避免body stream已读错误
问题核心原因
- Response的body是可读流,仅能被读取一次,你重复调用
json()方法自然会抛出「JSON body stream already read」错误 - 你当前的判断逻辑
if (!('https://a/'))永远为假,无法正确匹配对应的请求地址 - 每个Response实例仅对应单个请求的返回,你无法在同一个
json()方法调用中同时拿到两个不同请求的结果
可行实现方案
思路:外层定义两个变量分别存储两个接口的返回结果,重写json()方法时先把解析后的结果缓存到Response实例上避免重复读流,再根据当前返回对应的接口地址赋值到对应变量,两个变量都拿到有效值后自动执行对比逻辑。
// 缓存原生json方法 const originalJson = window.Response.prototype.json; // 外层声明变量存储两个接口的返回结果 let aResponse = null; let bResponse = null; window.Response.prototype.json = async function () { // 已缓存解析结果直接返回,避免重复读流 if (this._cachedJson) return this._cachedJson; // 调用原生方法解析结果,缓存到实例上 const result = await originalJson.call(this); this._cachedJson = result; // 匹配对应接口存储结果,可根据实际情况调整匹配规则 if (this.url.includes('https://a/')) { aResponse = result; } if (this.url.includes('https://b/')) { bResponse = result; } // 两个结果都获取完成后执行对比逻辑 if (aResponse && bResponse) { for (let detect in aResponse) { if (aResponse[detect] !== bResponse[detect]) { console.log(aResponse[detect]); console.log(bResponse[detect]); } } // 若需要多次对比可注释下方重置逻辑 aResponse = null; bResponse = null; } return result; };
注意事项
- 接口匹配规则可以根据实际需求调整,比如用
startsWith、正则匹配等替代includes - 缓存的
_cachedJson属性仅用于避免重复读取body流,不会影响原生请求的返回逻辑 - 若需要在其他逻辑中使用两个接口的返回值,直接调用外层的
aResponse和bResponse变量即可
内容的提问来源于stack exchange,提问作者user16856118
相关产品推荐
相关产品推荐

