Search code examples
ajaxnginxaxioscorsreverse-proxy

Proxy Server - Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present (First request works, second request doesn't)


I have a proxy server which I use for masking the domain, and it loads assets (When user visits server.com, through nginx, it's actually directing to server.com/123123).

The http requests works, however I am having a problem with ajax requests.

  • So, when I visit example.com, website works
  • When I do first POST (with ajax) request, it works (https://server.com/ajax/marketing/ajax/recaptcha/validate)
  • When I do second POST request (ajax), it doesn't work and says "Access to XMLHttpRequest at 'https://server.com/ajax/validate-order/H123HKK' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

In my server nginx (server.com), I have these headers:

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

In my example.com nginx, I have added:

proxy_set_header Host server.com;
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';

server {
   listen 443 ssl;
   listen [::]:443 ssl;

   server_name example.com;

   location = / {
       proxy_pass https://server.com/123123;
   }

   #Certs
   #ssl_certificate y.pem;
   #ssl_certificate_key x.pem;
}

My backend is Laravel however I am not sure if it's related to that.

What am I doing wrong so that one POST request works but other one doesn't? /validate-order/{orderId} should return a json so may that be the reason?


Solution

  • Apparently nginx doesn't add headers to error response codes; and there is a way to force it to add_header always

    add_header 'Access-Control-Allow-Origin' * always;
    

    Adding "always" keyword to all headers in my server, it worked!

    Big thanks to akawhy's answer.