跨原始資源共用(CORS)開發

透過用戶端JavaScript運用CORS從外部Web應用程式存取AEM內容的簡短範例。

此影片中:

  • www.example. commaps透過 /etc/hosts
  • aem-publish. localmaps透過localhost /etc/hosts
  • SimpleHTTPServer(Python的SimpleHTTPServer的包裝函式)正在通過埠8000為HTML頁提供服務。
    • Mac App Store中已不再提供。使用類似的方法,例如Jeeves
  • AEM Dispatcher 在2.4 Apache HTTP Web Server 上執行,且會向反向代理 aem-publish.local 請求 localhost:4503

如需詳細資訊,請檢閱AEM🔗中的了解跨原始資源共用(CORS)。

www.example.com HTML和JavaScript

此網頁的邏輯是

  1. 按一下按鈕時
  2. http://aem-publish.local/content/we-retail/.../experience/_jcr_content.1.json發出AJAX GET要求
  3. 從JSON回應中擷取jcr:title
  4. jcr:title插入DOM
<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>   
</head>
<body style="width: 960px; margin: 2rem auto; font-size: 2rem;">
    <button style="font-size: 2rem;"
            data="fn-getTitle">Get Title as JSON from AEM</button>
    <pre id="title">The page title AJAX'd in from AEM will injected here</pre>
    
    <script>
    $(function() { 
        
        /** Get Title as JSON **/
        $('body').on('click', '[data="fn-getTitle"]', function(e) { 
            $.get('http://aem-publish.local/content/we-retail/us/en/experience/_jcr_content.1.json', function(data) {
                $('#title').text(data['jcr:title']);
            },'json');
            
            e.preventDefault();
            return false;
        });
    });
    </script>
</body>
</html>

OSGi工廠配置

Cross-Origin Resource Sharing的OSGi配置工廠可通過以下方式獲得:

  • http://<host>:<port>/system/console/configMgr > Adobe Granite Cross-Origin Resource Sharing Policy
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    alloworigin="[https://www.example.com:8000]"
    alloworiginregexp="[]"
    allowedpaths="[/content/we-retail/.*]"
    exposedheaders="[]"
    maxage="{Long}1800"
    supportedheaders="[Origin,Accept,X-Requested-With,Content-Type,
Access-Control-Request-Method,Access-Control-Request-Headers]"
    supportedmethods="[GET]"
    supportscredentials="{Boolean}false"
/>

Dispatcher設定

若要允許快取內容上快取和提供CORS標頭,請在/clientheaders configuration後新增至所有支援AEM Publish dispatcher.any檔案。

/cache { 
  ...
  /clientheaders {
      "Access-Control-Allow-Origin"
      "Access-Control-Expose-Headers"
      "Access-Control-Max-Age"
      "Access-Control-Allow-Credentials"
      "Access-Control-Allow-Methods"
      "Access-Control-Allow-Headers"
  }
  ...
}

對檔案進行更改 後,重新啟動Web伺服器應 dispatcher.any 用程式。

/clientheaders配置更新後,可能需要完全清除快取,以確保在下一個請求上正確快取標題。

支援材料

本頁內容