简体   繁体   English

Firefox和Chrome的CORS错误

[英]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. 我在代码中遇到有关CORS错误的问题,我运行的.js文件给chrome和firefox提供了错误,但在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:*"); 我尝试添加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. 不要在客户端代码中添加xhr.setRequestHeader(“ Access-Control-Allow-Origin:*”)。

To allow cross domain request, the server simply needs to add the Access-Control-Allow-Origin header to the response. 要允许跨域请求,服务器仅需要将Access-Control-Allow-Origin标头添加到响应中。

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的值应该是要允许的请求的域名,或者如果允许任何源,则简单地*。

Access-Control-Allow-Origin: http://domain1.com OR 访问控制允许来源: http : //domain1.com

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. 如果要调用Web API方法,请参考以下经过测试的代码及其在其余API上的工作。

Client Side Code Ajax Call: 客户端代码Ajax调用:

 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. 在Web API项目中,您必须在Web.config文件中添加以下配置。 Under the system.webServer section add the following system.webServer部分下,添加以下内容

  <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 :) 希望这会有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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