%E3%80%82%20CORS%20%E9%9F%BF%E6%87%89%E6%A8%99%E9%A0%AD%E6%9C%AA%E9%80%9A%E9%81%8E.png)
我正在使用 Dokku 在 DigitalOcean 託管我的應用程式。 多庫運行 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 等)的情況下處理請求,那麼您的應用程式將更容易擴展,並且運行得更快。