danwoods
danwoods

Reputation: 4907

IE 11, XMLHttpRequest, and CORS

I'm trying to access an API service (via XMLHttpRequest/ajax) hosted on a sub-domain (ie: a client on app.samedomain.com will call out to api.samedomain.com) that requires specific headers to be set for security purposes, but I keep getting Access is denied errors. All the solutions I've found say the client/end user must add the site to the "Trusted Sites" security zone, but obviously this is not a real solution. What do I need to do to access an external site with specific headers?

Example Code:

var getUserById = function (user, callback, error) {
  $.support.cors = true; 
  var endpoint = _getApiVersion() + '/person/model/' + user.userId;
  var _headers = _setHeaders(endpoint, null, user, 'GET');
  $.ajax({
    type: 'GET',
    beforeSend: function (request)
    {
      request.setRequestHeader("api-key", _headers['api-key']);
      request.setRequestHeader("timestamp", _headers['timestamp']);
      request.setRequestHeader("content-md5", _headers['content-md5']);
      request.setRequestHeader("content-type", _headers['content-type']);
      request.setRequestHeader("signature", _headers['signature']);
      request.setRequestHeader("Access-Control-Allow-Origin", "*");
    },
    url: _getBaseUrl() + endpoint,
    data: null,
    contentType: 'application/json',
    dataType: 'json',
    success: callback,
    error: error
  });
};

Thanks in advance,
Dan

Upvotes: 1

Views: 1537

Answers (3)

tree
tree

Reputation: 401

Aside from that, it feels like an order of operations thing. All this should be before the callbacks.

type: 'GET',
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',

Upvotes: 0

Eric Tedj - MSFT
Eric Tedj - MSFT

Reputation: 975

"Access-Control-Allow-Origin" is a response header, not a request header. It is something that the server should send back to IE as part of the response.

If that still doesn't work, you might want to try firing up the F12 Network tool in the IE Dev tools to see if you can get more detail into where in the process the request is failing (Ex: It might be failing on a CORS preflight OPTIONS request).

Also, Rather than using "Access-Control-Allow-Origin: *", you should use "Access-Control-Allow-Origin:app.samedomain.com" to control which domains can access the API

To read more about CORS, check http://www.w3.org/wiki/CORS

Upvotes: 0

tree
tree

Reputation: 401

Are you trying to get data that is not in the same domain as the requester? If that is the case the only option is to proxy the original request via a service so XMLHttpRequest has access to it.

Upvotes: 2

Related Questions