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

如何在Cypress中处理HTTP/HTTPS协议及强制HTTPS重定向验证

验证强制HTTPS重定向的Cypress API及实践用法

以下几个Cypress API可以帮你验证HTTP到HTTPS的强制重定向流程:

1. cy.visit() + 断言最终URL

cy.visit() 默认会自动跟随重定向,你可以通过断言最终页面的URL协议来验证重定向是否生效:

cy.visit('http://your-app-domain.com')
cy.url().should('include', 'https://')
// 额外验证域名一致性(可选)
cy.url().should('eq', 'https://your-app-domain.com')

如果需要验证重定向的状态码,可结合cy.intercept()一起使用(见下文)。

2. cy.request() 检查重定向响应细节

通过禁用自动跟随重定向,你可以直接获取HTTP请求的重定向响应,验证状态码和跳转目标:

cy.request({
  url: 'http://your-app-domain.com',
  followRedirect: false // 禁止跟随重定向,直接拿到3xx响应
}).then((response) => {
  // 验证重定向状态码(通常是301永久重定向或302临时重定向)
  expect(response.status).to.be.oneOf([301, 302])
  // 验证跳转目标是HTTPS地址
  expect(response.headers.location).to.match(/^https:\/\/your-app-domain\.com/)
})

3. cy.intercept() 拦截并监控请求流

拦截原始的HTTP请求,验证它被触发,同时确认后续的HTTPS请求是否被发起:

// 拦截HTTP请求
cy.intercept('GET', 'http://your-app-domain.com').as('httpRequest')
// 访问HTTP地址
cy.visit('http://your-app-domain.com')
// 验证HTTP请求确实被发起
cy.wait('@httpRequest').then((interception) => {
  // 可选:验证HTTP请求的响应状态码是重定向类型
  expect(interception.response.statusCode).to.be.oneOf([301, 302])
})
// 最终验证页面处于HTTPS协议下
cy.url().should('include', 'https://')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:13:25