クロスオリジンリソース共有(CORS)に対応する開発

CORS を活用して、クライアントサイド JavaScript で外部 web アプリケーションから AEM コンテンツにアクセスする簡単な例です。

このビデオの内容は次のとおりです。

  • www.example.com/etc/hosts を介してローカルホストにマッピングされます。
  • aem-publish.local/etc/hosts を介してローカルホストにマッピングされます。
  • SimpleHTTPServer(Python の SimpleHTTPServer のラッパー)がポート 8000 で HTML ページを提供しています。
    • Mac App Store では入手できなくなりました。Jeeves など、類似のものを使用します。
  • AEM Dispatcher が Apache HTTP Web Server 2.4 で動作しており、aem-publish.local へのリクエストを localhost:4503 にリバースプロキシしています。

詳しくは、AEM でのクロスオリジンリソース共有(CORS)についてを参照してください。

www.example.com の HTML と JavaScript

この web ページには、次のようなロジックがあります。

  1. ボタンのクリック時に、
  2. http://aem-publish.local/content/we-retail/.../experience/_jcr_content.1.json に対して AJAX GET リクエストを実行します。
  3. JSON 応答から jcr:title フォームを取得します。
  4. DOM に jcr:title を挿入します。
<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 ヘッダーをキャッシュし提供できるようにするには、AEM パブリッシュのすべての dispatcher.any サポートファイルに次の /clientheaders configuration を追加します。

/myfarm {
  ...
  /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"
  }
  ...
}

dispatcher.any ファイルを変更した後、web サーバーアプリケーションを再起動​します。

/clientheaders 設定更新後の次のリクエストでヘッダーが適切にキャッシュされるようにするには、キャッシュを完全にクリアすることが必要です。

サポート資料

このページ