我能否在Chrome开发工具中模拟我的请求响应?

17

我正在调试仅发生在生产环境中的前端问题。我想知道是否有任何方法可以模拟请求的响应或模拟一些静态文件。

例如,

当我调用 xxx.com 时,它会加载 index.htmla.js。由于 Chrome 缓存了 js,是否可能我们可以模拟 a.js,以便 index.html 加载模拟的 a.js


我记得两年前我做过类似的事情,但是现在在开发工具中找不到这个部分了。 - pery mimon
4个回答

25

在开发工具本身中无法模拟服务器响应,但是有一些Chrome扩展可以帮助解决这个问题:

  1. 我尝试了其中的7个,但只有 (Tweak) 可以:
  2. 拦截需要的URL
  3. 设置Content-Type类型
  4. 设置有效载荷

tweak extension


1
这个扩展十分有用!我已经试过了,非常容易使用,谢谢! - Juampi Cáceres

4
你可以尝试使用Puppeteer,并结合page.setRequestInterception()request.respond()来操作。示例代码如下:
const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();

    await page.setRequestInterception(true);
    page.on('request', (interceptedRequest) => {
      if (interceptedRequest.url() === 'https://sb.scorecardresearch.com/beacon.js') {
        interceptedRequest.respond({
          body: 'document.title = "42";',
        });
      } else {
        interceptedRequest.continue();
      }
    });

    await page.goto('https://stackoverflow.com/help');

    // await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

2

截至Chrome 117版本,您可以在本地模拟Web内容。

要覆盖Web内容,请打开网络面板,右键单击请求,然后选择覆盖内容。

DevTools目前支持以下请求类型的内容覆盖:图像(例如avif,png),字体,fetch和XHR,脚本(css和js)以及文档(html)。DevTools现在会将不支持的类型的“覆盖内容”选项变为灰色。


1
一种解决方案是使用npm json-server。它会在每个请求中返回指定url上存储的json数据。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接