Andres Biarge
Andres Biarge

Reputation: 389

2 request instead of 1 from Google Chrome

We're building a SPA using vue.js and Node.js (Express). The SPA is downloaded from 1 domain and the REST api is in another one.

The issue is that I've noticed that Chrome does 2 request instead of 1 when doing an ajax call to another domain different from the one where the web page was downloaded (CORS request).

After doing some research, I've come to the conclusion that it's a feature, not a bug.

So, what should be the best approach to solve this in an elegant way?

I currently discard the first request with a 200 status response, but I don't think it's the best way to do this.

Upvotes: 1

Views: 1115

Answers (1)

Joe Clay
Joe Clay

Reputation: 35857

If the first request being sent is an OPTIONS request, it's most likely a CORS pre-flight. This is used by the browser to ask the server whether or not it is allowed to submit the actual request.

If your server is running business logic in response to a pre-flight, you've not implemented CORS properly - HTML5Rocks provides this handy flowchart of how it should actually work:

CORS flowchart

That might look a little overwhelming - thankfully, you don't have to worry about that, as there's already an official CORS middleware for Express which provides this functionality, and more. If you plug that in, you should be able to remove all the explicit res.header("Access-Control-Allow-Origin", "*") stuff from your application.

Upvotes: 3

Related Questions