Evert
Evert

Reputation: 99571

Sending a 'simple' POST request with jQuery, but getting CORS anyway

The CORS specification states that if a HTTP request is considered 'simple', no CORS and/or preflight is needed.

I'm trying to do a HTTP request that appears to have these conditions:

Code sample:

$.ajax({
  type: 'POST',
  url: 'http://example.org/',
  data: {foo: 'bar'}
});

However, when running this, the request is still preflighted with OPTIONS (which fails). Is there something obvious I'm missing?

A few references to simple requests:

Upvotes: 0

Views: 710

Answers (2)

Evert
Evert

Reputation: 99571

I realized my mistake when re-reading the documentation.

What I am doing is indeed a simple request. The request was actually being sent to the server without an OPTIONS request and succeeded!

However, I was not allowed to read the response when it came back. So the true difference between simple and non-simple CORS requests is:

For simple requests a preflight is not needed, but the server still needs to respond with CORS headers.

So my options are as follows:

  1. I ignore the error. The request succeeded after all, I just can't read the response.
  2. I implement CORS server-side anyway. In my case I can't, because I don't control the target server.
  3. I use a html form to submit the data, call .submit() on it and target a hidden iFrame.
  4. I proxy the request through a server that I do control.

Future:

I think, but I'm not sure, that the new Fetch API also allows a mode where you can make HTTP requests cross-domain, opt-out of CORS and simply be denied access to the HTTP response. If this is correct, then this would be the ideal way to do this (to me). But I don't know 100% certain if this is indeed how this works.

Upvotes: 0

TxRegex
TxRegex

Reputation: 2425

CORS restrictions affect all requests going from one domain to another. example: localhost -> example.com. I end up just going to my example.com server-side code and make sure I enable requests from myotherexample.com where I am making calls from. Do this using the CORS header while developing locally

Access-Control-Allow-Origin: *

Another example when you are ready for production

Access-Control-Allow-Origin: https://myotherexample.com

Upvotes: 1

Related Questions