Firefox blocked CORS while Chrome allowed, Nginx is used

Viewed 942

I want to make a AJAX call to a backend RESTful API server using XMLHttpRequest. The front-end is hosted by Apache. The API server is hosted by Django 2.0.9 (HTTP, I need to use Python) and HTTPS is provided by a Nginx (v1.4.6) reverse proxy, using self-signed cert.

The code for making calls to backend API is:

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);

In Chrome, it works. However in Firefox (I tested with version 61.0.1 64-bit), I got the error: "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)."

The config file used in Nginx is:

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';
        }
    }
}

There is a lot information information about CORS in the Internet but seems that I cannot find a way to fix this. Thank a lot.

0 Answers
Related