0

I have a problem regarding CORS error in my code,the .js file which I run gives error for chrome and firefox but not on IE. I have been suggested to add response headers to it but I am confused where to add it.Please help

xhr.open(method, url, true);

I tried adding xhr.setRequestHeader("Access-Control-Allow-Origin:*"); to it,will this work?

Neha
  • 11
  • 5
  • 1
    We need more information... But you can read about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – epascarello Feb 08 '16 at 17:43
  • 1
    Welcome to SO. Please visit the [help] to see what and how to ask. HINT: Post your efforts and error messages – mplungjan Feb 08 '16 at 17:46
  • Check this links http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm – brk Feb 08 '16 at 17:53

1 Answers1

4

Do not add the xhr.setRequestHeader("Access-Control-Allow-Origin:*") at the client side code.

To allow cross domain request, the server simply needs to add the Access-Control-Allow-Origin header to the response.

The value of the Access-Control-Allow-Origin should be the domain name of the request to be allowed or simply * if any origin is allowed.

Access-Control-Allow-Origin: http://domain1.com OR

Access-Control-Allow-Origin: *

If you are calling the Web API method then refer the below tested code and its working for the rest API.

Client Side Code Ajax Call:

function CallAjax() {
    
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:54118/api/values", true);
xhr.onload = function () {
    console.log(xhr.responseText);
    alert("sucuess");
};
xhr.send();
}

Server Side Changes :

In the Web API project you have to add the following configuration in the Web.config file. Under the system.webServer section add the following

 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>

This will allow any domain to access the resource.

Hope this will be helpful :)