同源策略与AJAX加载小部件

same-origin policy with AJAX load widget

本文关键字:加载 小部 AJAX 策略      更新时间:2023-09-26

我试图在我的网页中包含一个小部件。小部件的代码是用ajax动态加载的(因为它经常变化,我需要从服务器更新它),它看起来像这样…

<a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
<script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>

加载时,我在控制台中得到以下错误…

OPTIONS https://js.gleam.io/e.js 404 (Not Found)
XMLHttpRequest cannot load https://js.gleam.io/e.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 404.

如果我删除为小部件加载数据的ajax调用,而是直接插入小部件,我不会得到相同的错误,小部件工作正常。

我已经读到这一点,并认为这是由于同源策略(SOP),所以我现在想知道规避该策略的最佳方法。

我已经阅读了规避同源策略的方法,但不幸的是,在这种情况下没有发现它有帮助。

既然CORS是在服务器端完成的(我认为?)和JSONP是不安全的,是最好的选择创建代理吗?

非常感谢你的帮助。我花了好几个小时研究这个问题,但我还是很困惑。

编辑添加代码以获取更多信息:

当单击命令链接时,通过ajax加载页面信息,如下所示:

<h:commandLink action="#{redeemPerk.getDisplay(display.displayId)}" >
                    <h:graphicImage value="#{display.imgUrl}" styleClass="display-icon"/>
<f:ajax event="click" execute="@form" render="redeem-display-data-reveal" listener="#{redeemPerk.getDisplay(display.displayId)}" onevent="handleAjax"/>
</h:commandLink>

这将呈现显示小部件的区域,看起来像…

    <div class="reveal-modal-background hidden">
        <h:form id="redeem-display-data-reveal">
           <h:panelGroup rendered="#{display.type == 'WIDGET'}">
             <a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
           <script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>
        </h:form>
       </div></h:panelGroup>

第二个代码块位于与第一个单独的文件中。重申一下,如果我删除ajax调用并直接加载数据,小部件可以正常工作。

我在你的输出日志中看到两件可能导致这个问题的事情。

首先,它声明您收到了来自请求的404消息。这意味着JavaScript可能没有正确上传。

第二,它表示请求的来源来自localhost:8443。这使我相信你是在本地运行代码,而不是从互联网。

在你试图从互联网加载插件的情况下,但是你的代码正在本地测试,你仍然会得到一个SOP错误。要解决这个问题,你需要上传所有的代码,你有你的web服务器。一旦你这样做了,尝试从互联网上加载网页,而不是你的本地副本。这应该可以修复SOP错误。