Neha February 2016

CORS error for firefox and chrome

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?

Answers


Buddhabhushan Kamble February 2016

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 :)

Post Status

Asked in February 2016
Viewed 1,266 times
Voted 14
Answered 1 times

Search




Leave an answer