允许Chrome浏览器时,Firefox阻止了CORS,使用了Nginx

时间:2018-10-24 06:38:35

标签: google-chrome firefox nginx cors reverse-proxy

我想使用XMLHttpRequest对后端RESTful API服务器进行AJAX调用。前端由Apache托管。该API服务器由Django 2.0.9(HTTP,我需要使用Python)托管,而HTTPS由Nginx(v1.4.6)反向代理使用自签名证书提供。

调用后端API的代码为:

var formData = new FormData();
formData.append('data', 'I am data');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.mysite.com/api1/', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        /* handling response */
    }
};
xhr.send(formData);

在Chrome中有效。但是,在Firefox(我使用61.0.1 64位版本进行测试)中,出现了错误:"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mysite.com/api1/. (Reason: CORS request did not succeed)."

Nginx中使用的配置文件为:

server {
    listen 8443;
    server_name localhost;
    ssl on;
    ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
    ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
    location / {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        add_header 'Access-Control-Allow-Credentials' 'true';
        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';
        if ($request_method = 'OPTIONS') {
            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-Expose-Headers' 'Content-Length,Content-Range';
        }
        if ($request_method = 'GET') {
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
    }
}

Internet上有很多有关CORS的信息,但似乎找不到解决此问题的方法。非常感谢。

0 个答案:

没有答案