javascript 如何解决:被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53974853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:20:44  来源:igfitidea点击:

How to solve: Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

javascriptcorssalesforceapexvisualforce

提问by diwakar g

I am trying to call javascript using visualforce (VF) page. On clicking preview in VF page, method is executed. But, when I tried to see the response in Google chrome getting "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource" error. Below is the sample code for VF.

我正在尝试使用 Visualforce (VF) 页面调用 javascript。在 VF 页面点击预览,方法被执行。但是,当我尝试在 Google chrome 中看到响应时出现“被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头”错误。下面是 VF 的示例代码。

<apex:page controller="calljavascript_cls" >

<script>

function func()

{

var request = new XMLHttpRequest();

request.open('GET', 'https://copado.herokuapp.com/json/v1/webhook/metadata/AAAA?api_key=BBBB');

request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};

 request.send();


 }

 </script>

 <apex:outputText value="{!callfunc}" escape="false"></apex:outputText>

  </apex:page>

Apex controller class:

Apex控制器类:

public class calljavascript_cls

{

 public string callfunc{get;set;}


 public calljavascript_cls()

 {

   callfunc='<script> func(); </script>';

 }

 }

I tried the solutions given in below link. Not working.

我尝试了以下链接中给出的解决方案。不工作。

Link1Link2

链接1链路2

Don't know how to proceed. Please help me.

不知道如何继续。请帮我。

回答by vengleab so

You need to set header "Access-Control-Allow-Headers" on request, and your server must also allow set header "Access-Control-Allow-Headers", sth call CORS

您需要根据请求设置标头“Access-Control-Allow-Headers”,并且您的服务器还必须允许设置标头“Access-Control-Allow-Headers”,调用 CORS

request.setRequestHeader('Access-Control-Allow-Headers', '*');