Javascript XMLHttpRequest 被 CORS 策略阻止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46277295/
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-08-23 03:23:35  来源:igfitidea点击:

XMLHttpRequest blocked by CORS Policy

javascriptcors

提问by Prolativ

I add an API with following script in let's say http://www.test.com:

我在假设http://www.test.com 中添加了一个带有以下脚本的 API :

<script src="http://apiendpoint.com/api/v1/api.js"></script>

<div id="api" data-apikey="LA59CJI9HZ-KIJK4I5-3CKJC"></div>

api.js

api.js

$(function () {

  apikey = $('#api').data('apikey');
  $("#api").load("http://apiendpoint.com?apikey=" + apikey);

})

When I load the page, I get following error:

当我加载页面时,出现以下错误:

XMLHttpRequest cannot load apiendpoint URL. Redirect from 'apiendpoint URL' to 'apiendpoint URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'test URL' is therefore not allowed access.

XMLHttpRequest 无法加载 apiendpoint URL。从“ apiendpoint URL”重定向到“ apiendpoint URL”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“测试 URL”。

In the path of apiendpoint.com I added in .htaccess following code:

在 apiendpoint.com 的路径中,我在 .htaccess 中添加了以下代码:

Header set Access-Control-Allow-Origin "*"

But it does not work.

但它不起作用。

回答by foakesm

I believe sideshowbarker 's answer herehas all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

我相信sideshowbarker 在这里的答案包含解决此问题所需的所有信息。如果您的问题只是您收到的响应中没有“Access-Control-Allow-Origin”标头,您可以设置 CORS 代理来解决此问题。在链接的答案中提供更多信息