XMLHttpRequest 被 CORS 策略阻止

Posted

技术标签:

【中文标题】XMLHttpRequest 被 CORS 策略阻止【英文标题】:XMLHttpRequest blocked by CORS Policy 【发布时间】:2018-02-26 20:56:52 【问题描述】:

我在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

$(function () 

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

)

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

XMLHttpRequest 无法加载 apiendpoint 网址。 重定向自 'apiendpoint URL' 到 'apiendpoint URL' 有 被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头 存在于请求的资源上。起源 'test URL' 因此不允许访问。

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

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

但它不起作用。

【问题讨论】:

使用浏览器工具的网络选项卡检查是否存在标头 同时清除浏览器缓存。 从 chrome 商店下载 CORS 插件,打开后尝试发出请求。 @Ferrybig 响应标头不包含“Access-Control-Allow-Origin:*”。但是当我直接加载 URL 时,它包含 Access-Control-Allow-Origin:* 我相信sideshowbarker 's answer here 将拥有解决此问题所需的所有信息 【参考方案1】:

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

【讨论】:

【参考方案2】:

我知道这可能会迟到,但希望这对其他人有所帮助。这个问题来自后端,调用CORS。我使用java作为后端,所以我将@CrossOrigin添加到Controller类。有效!

【讨论】:

以上是关于XMLHttpRequest 被 CORS 策略阻止的主要内容,如果未能解决你的问题,请参考以下文章

从 Angular 前端到 json-server 的 GET 调用访问被 CORS 策略阻止的 XMLHttpRequest

CORS 策略已阻止从源访问“http://localhost...”处的 XMLHttpRequest:

从源“http://localhost:4200”访问“http://localhost:1111/...”的 XMLHttpRequest 已被 CORS 策略阻止:

当我的 xmlhttprequest 被 CORS 阻止时,我如何连接 api [重复]

访问 XMLHttpRequest 时访问 XMLHttpRequest 已被 CORS 策略阻止

CORS 策略已阻止从源对 X 的 XMLHttpRequest 的 CORS 访问