首页 > 解决方案 > 在 cypress 测试中请求路由时出现 CORS 错误

问题描述

我想模拟我的 SPA 完成的一些 API 调用。因此,我正在使用 cypress.JS 并使用以下测试检查如何做到这一点。

it("Then it works", () => {
    axios.defaults.baseURL = 'http://localhost';
    
    cy.server()
    cy.route("GET", "http://localhost/users/", true)
    
    axios.get("/users/").then(response => {
        console.log("received response: " + response)
        expect(response.body).to.equal(true)
    }).catch(error => console.log(error))
})

它不起作用我收到错误“从源 'http://localhost:8080' 访问 XMLHttpRequest 在 'http://localhost:8080' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin ' 请求的资源上存在标头。"

有没有办法在测试期间防止这个错误?我不明白为什么赛普拉斯会以可能发生此错误的方式处理这个简单的测试。

标签: corscypress

解决方案


在您cypress.json设置chromeWebSecurityfalse.

{
  "chromeWebSecurity": false
}

此处的 cypress 文档中,设置chromeWebSecurityfalse允许您执行以下操作:

  • 显示不安全的内容
  • 导航到没有跨域错误的任何超级域
  • 访问嵌入在您的应用程序中的跨源 iframe。

推荐阅读