You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Cypress intercept拦截除baseUrl外的所有外部请求?

如何在Cypress中拦截所有非本地(localhost:3001)的外部请求?

我有一个运行在http://localhost:3001的单页应用,已经把Cypress的baseUrl设为这个地址。现在想拦截所有外部请求——也就是目标地址不是localhost:3001的请求,但试了几种写法都没达到预期,反而把http://localhost:3001/_nuxt这类本地文件请求也拦截了。

我尝试过这些cy.intercept写法:

cy.intercept("**!(localhost:3001)*", (req) => {
cy.intercept("**!(localhost:3001)**", (req) => {
cy.intercept(/^((?!http:\/\/localhost:3001).+)$/, (req) => {
cy.intercept({ url: /^((?!.*localhost:3001).+)$/ }, (req) => {

奇怪的是,单独测试正则表达式/^((?!.*localhost:3001).+)$/是有效的:

  • 匹配本地地址时返回null,符合预期:
    /^((?!.*localhost:3001).+)$/.exec("http://localhost:3001/_nuxt/components/Component.vue") => null
    
  • 匹配外部地址时能正确捕获:
    /^((?!.*localhost:3001).+)$/.exec("https://www.example.com")
    // 返回结果:['https://www.example.com', 'https://www.example.com', index: 0, input: 'https://www.example.com', groups: undefined]
    

想请教:Cypress的intercept是不是有超出普通正则exec的匹配逻辑?还是我哪里考虑不周?另外,这种拦截所有外部请求的设计思路有没有问题?


内容的提问来源于stack exchange,提问作者Juho Rutila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:33:18