I've been struggling with CORS for a substantial amount of time, and still no closer to a full understanding.
My simplest example is using Wunderlist API -
Using the below code:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://a.wunderlist.com/api/v1/lists",
"method": "GET",
"headers": {
"x-client-id": "{ID}",
"x-access-token": "{TOKEN}",
"cache-control": "no-cache"
},
"data": "{\n\t\"revision\": 1,\n\t\"completed\": true\n}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Within Postman/Fiddler will return results. However, throwing it onto a basic site, or Codepen will either return a 405
, a Pre-flight Warning
or an Invalid Request
I've loosely come to the understanding that you allow it within your server side, but I have to assume that not every single site out there allows for Postman etc to connect, nor for every vendor I sign up with it allow my domain.
How is it you work on bypassing the CORS Compliance within an API Call then? I've tried a lot of things I've read, including crossDomain, Cross-Origin Header, etc and always get same result.
Any insight?
The reason it's being flagged for preflight is the extra headers you are sending. GET
requests do not have to use a preflight request unless you are passing custom headers. You have two options:
The simplest solution is to remove the custom headers you are attempting to send, and the request should no longer get flagged as requiring CORS preflight.
If you are hosting the server code, you can check the incoming request (server-side) to see if it has request method OPTIONS
. If so, you know this is the preflight and should respond with a response that tells the client what headers are acceptable. To allow all custom headers, the preflight response should contain a 'Access-Control-Request-Headers': '*'
response header.
Per https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS:
UPDATE: Per https://developer.wunderlist.com/documentation/concepts/authorization you have to register your application for it to be able to talk to them. Somewhere in that process they may automatically start sending preflight requests for your domain or allow you to set the headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With