简体   繁体   中英

CORS - Laravel on UBuntu 18.04 Via AJAX

I have two local domains (domainone.io and domaintwo.io ) and I would like to allow CORS between both.

On the server I did allow it by :

server {
    listen    80;
    listen [::]:80;
    server_name domainone.io;
    root /media/....../domain1/public;
    index index.php index.html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        # With php7.0-cgi alone:
        #fastcgi_pass 127.0.0.1:9000;
        # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

    location / {
        add_header 'Access-Control-Allow-Origin' 'domaintwo.io';
        add_header 'Access-Control-Allow-Methods' 'POST';
        add_header 'Access-Control-Allow-Methods' 'Content-Type';
        try_files $uri $uri/ /index.php?$query_string;
    }
}

And on the second domain :

server {
    listen    80;
    listen [::]:80;
    server_name domaintwo.io;
    root /media/....../domain2/public;
    index index.php index.html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        # With php7.0-cgi alone:
        #fastcgi_pass 127.0.0.1:9000;
        # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

    location / {
        add_header 'Access-Control-Allow-Origin' 'domainone.io';
        add_header 'Access-Control-Allow-Methods' 'POST';
        add_header 'Access-Control-Allow-Methods' 'Content-Type';
        try_files $uri $uri/ /index.php?$query_string;
    }
}

ISSUE:

When I make an ajax call from either domain, I still get the CORS not enabled error message, specifically:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domainone.io/test . (Reason: CORS header 'Access-Control-Allow-Origin' missing)

My JS is something like:

<script>
$(document).on('click', '.btn', function() {
  var someX = "lol";
  var token  = $('[name="csrf-token"]').prop("content");
  $.ajax({
    url: 'http://domaintwo.io/test',
    type: 'POST',
    data: {_token: token, test:someX },
    dataType: 'JSON',
    success: function(response) {
      alert(JSON.stringify(response));
    },
    error: function() {

    }
  });
});
</script>

我认为安装laravel-cors将解决您的问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM