Question

Laravel 8 API on LEMP(Nginx) Droplet CORS

I’ve scoured the this site and Stack Overflow but I cant find a solution that works.

I have a simple Laravel 8 API that is hosted on an Ubuntu server using Nginx.

The application is deployed and works through postman, However, when i try to use a simple front end axios get request for the same URL I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.xxx.xxx/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I have realised that the request from the front end app is not even getting through to index.php. I tried to log out a simple message and got nothing.

This leads me to believe this issue is Nginx related. My sites-available file for the project is below:

server {
     server_name xxx.xxxxx.xxxxxxxx;
     root /var/www/xxx.xxxxx.xxxxxxxx/public;
 
     index index.html index.htm index.php;
 
     charset utf-8;
 
     location / {
         try_files $uri $uri/ /index.php?$query_string;
     }
 
     location = /favicon.ico { access_log off; log_not_found off; }
     location = /robots.txt  { access_log off; log_not_found off; }
 
     error_page 404 /index.php;
 
     location ~ \.php$ {
         fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
         fastcgi_index index.php;
         fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
         include fastcgi_params;
     }
 
     location ~ /\.(?!well-known).* {
         deny all;
     }
 
     listen 443 ssl; # managed by Certbot
     ssl_certificate /etc/letsencrypt/live/xxx.xxxxx.xxxxxxxx/fullchain.pem; # managed by
      Certbot
     ssl_certificate_key /etc/letsencrypt/live/xxx.xxxxx.xxxxxxxx/privkey.pem; # managed >     by
     Certbot
     include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
     ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
 
 
     } server {
     if ($host = xxx.xxxxx.xxxxxxxx) {
         return 301 https://$host$request_uri;
     } # managed by Certbot
 
 
     listen 80;
     server_name xxx.xxxxx.xxxxxxxx;
     return 404; # managed by Certbot
 
 
     }

If anyone thinks im barking up the wrong tree or has any advice please let me know. I’m a bit stumped!

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi @damdigital3423,

Are you using the api.php route file? In addition ensure that CSRF is disabled for the api route group. Edit the app\Http\Middleware\VerifyCsrfToken as follows:

protected $except = [
    'api/*'
];

Hope helps you, Sergio Turpín