能否在Chrome控制台修改网站基础URL?后端API测试需求
在Chrome控制台拦截并修改API请求域名
当然可以通过Chrome控制台直接修改请求域名,不用麻烦前端改代码。核心思路是重写浏览器的请求API(fetch和XMLHttpRequest),在请求发送前替换目标域名。
方法一:重写fetch API(现代项目常用)
大部分现代前端项目用fetch发送请求,你可以在控制台粘贴以下代码,自动替换域名:
// 保存原生fetch方法 const originalFetch = window.fetch; // 重写fetch,替换请求域名 window.fetch = function(url, options) { // 把live.com替换成你的本地服务地址(记得加端口,比如localhost:3000) const targetDomain = 'https://live.com'; const localDomain = 'http://localhost:3000'; const modifiedUrl = url.replace(targetDomain, localDomain); // 调用原生fetch发送修改后的请求 return originalFetch(modifiedUrl, options); };
执行后,页面所有通过fetch发送的请求都会自动把live.com替换成你的本地地址。
方法二:重写XMLHttpRequest API(兼容老项目)
如果项目还在使用传统的XMLHttpRequest,补充这段代码覆盖:
// 保存原生XMLHttpRequest.open方法 const originalXhrOpen = XMLHttpRequest.prototype.open; // 重写open方法,替换请求域名 XMLHttpRequest.prototype.open = function(method, url, async, user, password) { const targetDomain = 'https://live.com'; const localDomain = 'http://localhost:3000'; const modifiedUrl = url.replace(targetDomain, localDomain); // 调用原生open方法 originalXhrOpen.call(this, method, modifiedUrl, async, user, password); };
额外提示
- 持久化修改:如果不想每次打开页面都粘贴代码,可以用Tampermonkey这类用户脚本工具,把上述代码写成脚本,设置只在公司管理后台域名下自动运行。
- 跨域问题处理:如果本地API没有配置CORS,浏览器会报错。解决方式要么在本地服务端配置允许管理后台域名的跨域请求,要么用Chrome的开发模式启动参数(比如
--disable-web-security --user-data-dir=/tmp/chrome-dev),注意后者仅适合开发环境。 - 灵活匹配域名:如果需要匹配HTTP和HTTPS的
live.com,可以用正则表达式:url.replace(/https?:\/\/live\.com/g, 'http://localhost:3000')
内容的提问来源于stack exchange,提问作者Sheikh Abdullah
相关产品推荐
相关产品推荐

