corsnginx-reverse-proxy

Unable to configure NGINX to handle CORS


I am using Weblow in frontend (www.example.com) and a separate server to serve backend data via JSON (api.example.com).

I use Nginx and my configuration is as per below:

server {
 server_name api.example.com;
 index file.json;

location / {
    root /var/www/example/html;
    default_type application/json;
    add_header Content-Type application/json;
    add_header Access-Control-Allow-Methods "*";
    add_header Access-Control-Allow-Methods "*";
 }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
    include /etc/l
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "*";
    if ($host = api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


 listen 80;
 server_name api.example.com;
    return 404; # managed by Certbot


}

My frontend code looks something like below:

var xmlhttp = new XMLHttpRequest();
var url = "https://api.example.com";

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        console.log(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
xmlhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xmlhttp.send();

But my request has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, my request still kept blocked by CORS.

Would like to know what's wrong with my code above?

Thanks a lot in advance.

I have tried to add header allowing CORS in Nginx but not working.


Solution

  • I get it solved. My configuration of Nginx looks like below:

    location / {
    add_header Content-Type application/json;
    add_header Access-Control-Allow-Methods "*";
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Headers "*";
    if ($request_method = OPTIONS){
        return 204;
    }
    root /var/www/example/html;
    default_type application/json;
    

    }