Pregunta

I have an ASP.Net MVC 4 Website and another ASP.Net Web API project.Currently both are hosted on different domain.I am using amplify.js to consume API on my front end.Since both websites are hosted on different domain its always a crossdomain request when i call my API from the UI(I am utilizing CORS for this purpose.).This results in additional OPTIONS request for each HTTP API call i make,which increases overhead.I also tried hosting these 2 websites on sub domains but still the OPTIONS request is there,I want to get rid of these extra request.

Is there any way by which i can eliminate the OPTIONS request?

¿Fue útil?

Solución

Is there any way by which i can eliminate the OPTIONS request?

You could use JSONP instead of CORS. Unfortunately this might not be sufficient for your scenario because JSONP works only with GET requests (jQuery's $.ajax method has this limitation).

Or if you host the 2 on the same domain and you are not violating the same origin policy, you could use a normal AJAX request.

Otros consejos

To prevent a cross-domain request, origin and target domain must be exactly the same: in host, domain and port (same origin policy). However, you have some options to prevent CORS anyway:

  1. Put website and API in the same domain - kinda obvious ;)
  2. Create some kind of serverside proxy-script (PHP, Node.js or whatever you like), which routes the request via curl or anything similar to the API. This should prevent the OPTIONS headers, but needs another HTTP request (AJAX <-> website httpd <- > API httpd).
  3. A similar solution is to use Apache as a reverse proxy (howto here). Like the script solution this also results in two HTTP requests, but I assume a reverse proxy causes less overhead.
  4. You could also use JSONP, but the API need to support it (so you might have to reimplement the website<->API communication) and your API won't be RESTful anymore (if you care about it).

I would go either way one or way three as the script solution just feels too clumsy ;) I would also suggest to check whether it is really necessary to run API and website on different domains. The OPTIONS header usually don't cause too much overhead so you might consider to optimize other parts of your code first.

Maybe you could put the website and the API in one domain and only the database for the API on another server? Just an idea...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top