简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM