Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS Error when requesting route in cypress test

Tags:

cors

cypress

I would like to mock some of the API calls done by my SPA. Therefor I am using cypress.JS and checked how to do this by using following test.

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))
})

It does not work I get the error "Access to XMLHttpRequest at 'http://localhost/users/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Is there any way to prevent this error during tests? I don’t understand why Cypress is handling this simple test in a way that this error can occure.

like image 289
HerrLoesch Avatar asked May 03 '19 15:05

HerrLoesch


2 Answers

In your cypress.json set chromeWebSecurity to false.

{
  "chromeWebSecurity": false
}

As from cypress documentation here, setting chromeWebSecurity to false allows you to do the following:

  • Display insecure content
  • Navigate to any superdomain without cross origin errors
  • Access cross origin iframes that are embedded in your application.
like image 159
Diogo Rocha Avatar answered Oct 11 '22 17:10

Diogo Rocha


The issue was, that I configured cypress with base url localhost:8080

{
  "baseUrl": "http://localhost:8080"
}

but used only local host in my test

   it("Then it works", () => {

    cy.server()           
    cy.route({
        method: 'GET',     
        url: '/users/1',    
        response: true        
    })

    axios.get("http://localhost:8080/users/1").then(response => {
        console.log("received response: " + response)
        expect(response.body).to.equal(true)
    }).catch(error => console.log(error))
})

The test is still not working but my initial question is answered. The error occured because the port was missing. I will update this when I found a solution for my other problem.

like image 3
HerrLoesch Avatar answered Oct 11 '22 17:10

HerrLoesch