Cypress无法调用不同localhost端口的HTTP XHR请求问题
问题:Angular 18应用在Cypress测试中无法调用后端API
- 环境信息:Node.js 20.18.0,Angular 18
- 场景:本地通过
npm run start启动Angular应用(访问地址http://localhost:4200/),编写了简单Cypress测试用例用于访问首页并检查应用标题 - 异常现象:执行
cypress open --browser chrome运行测试时,Angular应用无法调用部署在http://localhost:16105/的后端API;直接用curl调用该后端端点可正常返回结果,且应用加载时发起的多个API请求均出现相同失败问题 - 当前
cypress.config.ts配置:
import { defineConfig } from 'cypress'; export default defineConfig({ projectId: "XXXXX", defaultCommandTimeout: 10000, requestTimeout: 10000, chromeWebSecurity: false, retries: { runMode: 3, openMode: 0, }, e2e: { baseUrl: 'http://localhost:4200', experimentalStudio: true, excludeSpecPattern: "*.js", specPattern: ["cypress/e2e/**/+(all.ts|*.cy.ts)", "cypress/e2e/**/**/*.cy.ts)"] }, });
解决方法
1. 配置Cypress代理转发
在cypress.config.ts的e2e配置中添加setupNodeEvents,设置代理规则将前端API请求转发到后端:
e2e: { baseUrl: 'http://localhost:4200', experimentalStudio: true, excludeSpecPattern: "*.js", specPattern: ["cypress/e2e/**/+(all.ts|*.cy.ts)", "cypress/e2e/**/**/*.cy.ts)"], setupNodeEvents(on, config) { on('before:browser:launch', (browser = {}, launchOptions) => { if (browser.family === 'chromium' && browser.name !== 'electron') { // 把前端请求代理到后端地址 launchOptions.args.push(`--proxy-server=http://localhost:16105`); } return launchOptions; }); }, }
注意:如果Angular应用中API用的是相对路径(如/api/user),此配置生效;若用绝对路径,需调整为相对路径或用下面的拦截重写。
2. 用Cypress拦截重写API地址
在测试用例中添加请求拦截,将前端发起的API请求地址替换为后端真实地址:
beforeEach(() => { // 拦截所有GET类型的API请求,重写地址 cy.intercept('GET', 'http://localhost:4200/api/**', (req) => { req.url = req.url.replace('http://localhost:4200', 'http://localhost:16105'); }); // 按需添加POST/PUT/DELETE等其他请求方法的拦截 cy.intercept('POST', 'http://localhost:4200/api/**', (req) => { req.url = req.url.replace('http://localhost:4200', 'http://localhost:16105'); }); });
3. 检查后端CORS设置
即便chromeWebSecurity设为false,部分后端框架仍会严格校验请求来源。确保后端允许http://localhost:4200作为跨域请求的Origin,测试环境可临时放宽CORS限制。
4. 确认后端服务状态
测试前务必确认http://localhost:16105/的后端服务已正常启动,且没有被本地防火墙、代理工具(如Charles)拦截请求。
内容的提问来源于stack exchange,提问作者HamidIng
相关产品推荐
相关产品推荐

