Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preflight, or CORS error, on every request

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?

like image 342
DNorthrup Avatar asked Dec 21 '16 00:12

DNorthrup


Video Answer


1 Answers

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:

  1. 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.

  2. 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:

enter image description here

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.

like image 148
cchamberlain Avatar answered Sep 21 '22 04:09

cchamberlain