Cypress 12.3.0代理配置失效:无法通过代理访问目标URL
Cypress 12.3.0 代理配置不生效解决方案
问题分析
Cypress 默认不会自动继承系统或 env 中的代理配置,需针对**API 请求(cy.request)和页面加载(cy.visit)**分别配置,同时要避免影响内网地址访问。
1. 针对 cy.request 的代理配置
cy.request 不会自动读取 http_proxy 变量,需通过 Node.js 代理包手动配置:
步骤:
- 安装代理依赖包:
npm install http-proxy-agent --save-dev - 修改
cypress.config.js,在钩子中为特定 URL 绑定代理:const { defineConfig } = require('cypress') const { HttpProxyAgent } = require('http-proxy-agent') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 在请求发送前注入代理 on('before:request', (request) => { // 仅对目标URL启用代理 if (request.url.includes('你的特定目标URL关键词')) { const proxyUrl = config.env.http_proxy request.agent = new HttpProxyAgent(proxyUrl) } }) }, env: { http_proxy: 'http://some_proxy:8080' } } })
2. 针对页面加载(cy.visit)的代理配置
测试页面加载时,需为 Cypress 启动的浏览器实例指定代理参数,同时排除内网地址避免冲突:
配置示例(适用于 Electron/Chrome/Edge):
const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { browserLaunchOptions: { args: [ // 设置代理服务器 `--proxy-server=${process.env.http_proxy || 'http://some_proxy:8080'}`, // 排除内网地址不走代理(替换为你的内网域名) `--proxy-bypass-list=<-loopback>;*.your-company-intranet.com` ] }, env: { http_proxy: 'http://some_proxy:8080' } } })
3. 关键注意事项
- 代理地址需完整包含协议(http/https)和端口,若需认证,格式为
http://username:password@some_proxy:8080 - 确保
proxy-bypass-list正确配置内网域名,避免内网请求被错误转发到代理 - 可通过 Cypress 控制台的「Network」面板验证请求是否走代理:查看请求的「Proxy」字段或请求来源
内容的提问来源于stack exchange,提问作者Mukul Aggarwal
相关产品推荐
相关产品推荐

