1

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.

Andres Biarge
  • 370
  • 4
  • 15
  • Have you read this? https://stackoverflow.com/questions/4460661/what-to-do-with-chrome-sending-extra-requests – Ron van der Heijden Feb 27 '18 at 16:12
  • Yes, i have! Thx for your answer. I've posted this question after trying what that post talks about... I may be missing something else... I have also taken a good look in case I was doing 2 AJAX calls instead of one, but that is not the case. I'm pretty sure it's not a programming fault as I always attach in the body of the POST a JWT and the doubled request doesn't. – Andres Biarge Feb 27 '18 at 16:16
  • Is the first request an `OPTIONS` request (as opposed to a `GET` or a `POST`)? If so, that's most likely a [CORS preflight request](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request), which the browser uses to determine if it's allowed to send the actual request. Your server, ideally, should just return CORS headers in response to this. If your business logic is getting called twice, your server isn't implementing CORS correctly. – Joe Clay Feb 27 '18 at 16:18
  • That look's definately it, thank you. I don't know much about CORS so don't know how to handle it. I do handle it server side with the appropiate res.header("Access-Control-Allow-Origin", "*"); and so... Is it possible to avoid this first request as my API does accept CORS? – Andres Biarge Feb 27 '18 at 16:24
  • Hang on, writing an answer. – Joe Clay Feb 27 '18 at 16:25

1 Answers1

3

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.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85