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

如何在Cypress中拦截请求并路由至指定端点?

如何将Cypress拦截的请求重定向到另一个端点?

你可以通过cy.intercept的请求回调函数,修改请求的URL并让它继续发送到目标端点,这样应用就能获取/i18n/en.json的真实响应,无需依赖fixture。

方法一:直接修改请求URL(推荐)

这种方式会将原请求的目标地址替换为/i18n/en.json,让浏览器实际发起对该端点的请求,返回真实的后端响应:

cy.intercept('**/i18n/nl.json', (req) => {
  // 替换URL中的nl.json为en.json
  req.url = req.url.replace('/i18n/nl.json', '/i18n/en.json');
  // 继续发送修改后的请求
  req.continue();
}).as('Language');

方法二:主动请求目标端点后返回响应

如果需要对目标响应做额外处理,可以先通过cy.request获取/i18n/en.json的内容,再将其返回给原请求:

cy.intercept('**/i18n/nl.json', async (req) => {
  // 请求目标端点的内容
  const targetResponse = await cy.request('/i18n/en.json');
  // 将目标响应的body返回给原请求
  req.reply(targetResponse.body);
}).as('Language');

两种方式都能避免维护fixture的麻烦,让测试更贴近真实业务场景,其中方法一更简洁直接,推荐优先使用。

内容的提问来源于stack exchange,提问作者E. E. Ozkan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:50:36