0

Code dump:

$.ajax({
   type: 'GET',
   dataType: 'json',
   url: api,
   xhrFields: {
     withCredentials: true
   },
   beforeSend: function (xhr) {
     xhr.setRequestHeader('Authorization', "Basic [my auth token]");
   },
   success: function(jd) {
      console.log(jd.stringify());
   }
});

The problem is that Chrome and Firefox send an OPTIONS preflight when I include a beforeSend, however that OPTIONS request is refused by the API because it doesn't know how to handle an OPTIONS request and treats it like a GET, sees no Authorization header and refuses the request.

The only way I can get this to work is to coerce the browser either to not send an OPTIONS request or include my header with it. I am unable to modify the API that I am using.

I would appreciate it if anyone could advise me.

  • 1
    An OPTIONS request is sent before a cross-domain request to ensure that CORS headers are in place on the response. Firstly, are you intending to make a cross domain request? Secondly, do you have control of the receiving server? – Rory McCrossan Jan 07 '17 at 21:18
  • Yes I am intending to do cross domain (it's an API request) and no, I can't control the server: "I am unable to modify the API that I am using." – Felix Johnson Jan 07 '17 at 22:12
  • In this case I'm afraid what you're trying to do is not possible through JS code. The OPTIONS request fails because the responding server is not setup to send CORS headers in the response, ergo they do not allow requests to their API from third party domains. You will instead need to make the request server side. – Rory McCrossan Jan 07 '17 at 22:18
  • If you check the console you'll most likely see an error along the lines of `“No 'Access-Control-Allow-Origin' header is present on the requested resource”`, if so check out this question for an explanation of the problem: http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource. – Rory McCrossan Jan 07 '17 at 22:20
  • I know that the API is meant to handle 3rd party requests, because that's literally what it was created for! It's fully documented with request tokens etc – Felix Johnson Jan 09 '17 at 08:01
  • Have you checked to see if you get the above error in the console? – Rory McCrossan Jan 09 '17 at 08:02

1 Answers1

0

The reason why browser sends preflight request is that you are using custom headers. Please. read about how to avoid preflight request (content type should be text or html and no custom headers) If you could not chagne server side the last chance to make it work is to create your custom proxy (for example you can create node server and that node app would take your requests and forward them to those Api Then you will have you own server even in the some domain and this proxy server will send CORS requests to another server domain.

Romick
  • 163
  • 1
  • 1
  • 11