%E3%80%82CORS%20%E5%BF%9C%E7%AD%94%E3%83%98%E3%83%83%E3%83%80%E3%83%BC%E3%81%8C%E9%80%9A%E9%81%8E%E3%81%97%E3%81%AA%E3%81%84.png)
私は DigitalOcean でアプリをホストするために Dokku を使用しています。 ドックnginx 1.6 を実行して、Heroku のような環境をシミュレートする Docker アプリをプロキシします。アプリはすべて、以下のように同様のデフォルト設定を共有します。
私のNode.jsサーバーはCORS ミドルウェアブラウザに www.myapp.com が api.myapp.com を呼び出すことを許可するように指示します。
これは私のローカル コンピューターでは問題なく動作します。デプロイすると、ブラウザーに CORS エラーが表示されます。
XMLHttpRequest cannot load https://api.myapp.com/r_u_up. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.myapp.com' is therefore not allowed access. The response had HTTP status code 502.
ということで、WTF、終了。
私はこれを見つけましたnginx CORS 設定しかし、非常に不格好に思えます。これは古いコードですか、それとも最善の方法ですか? これプラグインはその設定を使用します。
応答ヘッダーをそのまま渡すだけの、よりシンプルな構成を希望します。私のアプリでは、応答ヘッダーをインターセプトするために nginx は必要ありません。どのように構成すればよいでしょうか?
アプリの nginx.conf:
upstream www { server 172.17.0.135:5000; }
server {
listen [::]:80;
listen 80;
server_name www.myapp.com ;
return 301 https://www.myapp.com$request_uri;
}
server {
listen [::]:443 ssl spdy;
listen 443 ssl spdy;
server_name www.myapp.com;
keepalive_timeout 70;
add_header Alternate-Protocol 443:npn-spdy/2;
location / {
proxy_pass http://www;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection upgrade;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Request-Start $msec;
}
include /home/dokku/www/nginx.conf.d/*.conf;
}
答え1
更新: CORS はゾンビ化したウォーキング・デッドのような狂気の仕様であることが判明しました。そして、確かにこれを nginx 構成で実行するのが最善の方法です。
nginx が最善の方法である理由は、nginx が最も高速でクライアントに最も近いプロセスであるためです。
nginx がアプリ (node.js、php、rails など) に触れることなくリクエストを処理できる場合、アプリはより簡単に拡張でき、より高速に実行されます。