我有一个 Web 应用程序和服务器,它们在调试环境中完全正常运行,但是当它托管用于生产时,我在浏览器控制台中收到以下错误:
跨源请求被阻止:同源策略不允许读取远程资源https://api.mydomain.com/api/search. (原因:CORS 请求未成功)
客户端是一个 Javascript 应用程序(可通过 mydomain.com 访问),它向 API 服务器(Flask 应用程序,可通过 api.mydomain.com 访问)发出获取请求
javascript 获取请求的格式如下:
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
mode: "cors"
})
Flask 服务器已启用 CORS:
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
这是 Nginx 配置:
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name mydomain.com api.mydomain.com www.mydomain.com;
location /api/ {
include proxy_params;
proxy_pass http://unix:/home/adminuser/mydomain_server/mydomain/server/mydomain.sock;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
location / {
# CORS
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
proxy_pass http://127.0.0.1:3030;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
}
server {
listen 80;
listen [::]:80;
server_name mydomain.com api.mydomain.com www.mydomain.com;
return 302 https://$server_name$request_uri;
}
奇怪的是,其中一个 GET 请求运行正常,另一个 GET 请求最初因 CORS 错误而失败,但经过一段时间后即可运行。我不知道问题出在哪里。