0

I am wanting to send an AJAX POST request from domain.com to sub.domain.com. I know that I need to enable CORS, however after reading online I am unsure if this needs to be done on the sending server or the receiving server, or both?

Could I just add the below to my receiving servers nginx?

if ($request_method = 'POST') {
  add_header 'Access-Control-Allow-Origin' 'domain.com';
  add_header 'Access-Control-Allow-Methods' 'POST';
}

Does something need to be set on the sending servers configuration, or is just doing this in the code sufficient?

$.ajax({
  type: "POST",
  url: sub.domain.com,
  data: data,
  success: success,
  dataType: dataType
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
TheOne745665
  • 417
  • 2
  • 6
  • 13
  • 2
    CORS always needs to be set on the receiving server only. – Rory McCrossan Apr 09 '19 at 07:28
  • 2
    There's no sending server here, the sender is a browser, on a user's machine - i.e. it's a client. The request goes directly from that browser to the receiving server. no other server is involved – ADyson Apr 09 '19 at 07:33

1 Answers1

0

I don't think that nginx will automatically allow requests from any all subdomains of domain.com. You can achieve this using regular expressions and pattern matching though:

server {

    root /path/to/your/stuff;

    index index.html index.htm;

     set $cors "";

    if ($http_origin ~* (.*\.domain.com)) {
        set $cors "true";
    }

    server_name domain.com;

    location / {

        if ($cors = "true") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Methods' 'POST';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
        }
}

After doing this I don't think that you will need to change anything in the sending configuration.

MrfksIV
  • 900
  • 6
  • 16