skip to Main Content

I am having my APIs (built using Laravel 8 Framework) hosted in a subdomain – webapi.somedomain.com. And am running a local version of Frontend UI built using React Framework and Axios library for the HTTP Requests. I have hosted in a Shared Hosting space (cPanel + CentOS)
I am facing an issue while hitting the hosted APIs. I have stated the error I see below:

Access to XMLHttpRequest at 'http://webapi.somedomain.com/api/authorization/signup' from origin 'http://localhost:3000' 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.

So I added the Laravel Custom CORS middleware; updated the files and cleared the cache using php artisan config:cache. Didn’t work out.
Couldn’t find any other resources. So I added the Laravel CORS package – fruitcake/laravel-cors. Have installed it, published it and added it to the middleware; updated the file and cleared the cache. But still I see the CORS error when hitting the APIs from my React project

config/cors.php:

    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,

Kernel.php:

    protected $middleware = [
        ...
        FruitcakeCorsHandleCors::class,
    ];

Am just a beginner in Laravel. What am I doing wrong? Can someone help me out? Thanks in advance.

P.S.: I totally understand what CORS is and how it works. I m new to Laravel. Not new to development. I wanna know what else should I be doing, and whether I am leaving out something.

3

Answers


  1. Chosen as BEST ANSWER

    The issue is because of the .htaccess file.

    In a shared hosting server it is important to have only the public folder of your project accessible in the public_html folder and the rest hidden in private.

    Link your index.php to the autoload.php that is in private (public non-accessible place - root folder or any folder thats outside public_html)

    When adding a Laravel project to a shared hosting workspace, it is important to add a few rules to the .htaccess file in the public folder which is inside the public_html folder of your hosting workspace.

    Finally the .htaccess file should look something like this:

    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
           Options -MultiViews
       </IfModule>
       Options +FollowSymlinks
       RewriteEngine On
    
       # Redirect Trailing Slashes...
       RewriteRule ^(.*)/$ /$1 [L,R=301]
    
       # Handle Front Controller...
       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteRule ^ index.php [L]
    </IfModule>
    
    RewriteEngine On
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
    

    Only after this you will be able to run queries to the Laravel routes. If not only the index.php will get executed and the other routes will not be recognized.

    This might be a known one. But as I was a beginner, I couldn't figure this out. Adding this as the answer in case any other beginner is facing the same problem. Cheers.


  2. If you are using apache2 to serve your laravel application then it could be an issue with the conf file of domain/subdomain which serves your application

    to allow usage of .htaccess you need to add block to your conf file after block end tag. something like the following:


    // File: /etc/apache2/sites-available/example.com.conf
    // File: /etc/apache2/sites-available/example.com-le-ssl.conf
    
    ....
    </VirtualHost>
    <Directory /var/www/html/example.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    

    make sure to revision your project path and make sure to include this block in both of your conf files in case your project is served with SSL [https]

    Now any configuration in your .htaccess file will be applied

    Login or Signup to reply.
  3. Add this into your .htaccess which is located with your index.php
    and
    Change domain name with your website name in below code(Header add Access-Control-Allow-Origin: "https://typeHEREyour.com&quot😉

    Code:

    For CORS Configuration

    # Add Font Types
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-font-ttf        .ttf
    AddType application/x-font-opentype  .otf
    AddType application/font-woff        .woff
    AddType application/font-woff2        .woff2
    
    <IfModule mod_headers.c>
        <FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
            ## un-remark this one for all access and remark out the one below it
            #Header set Access-Control-Allow-Origin "*"
            ## Change this to your local host url. and https or http
            Header add Access-Control-Allow-Origin: "https://typeHEREyour.com"
            Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
            Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
        </FilesMatch>
    </IfModule>
    
    # Remove index.php from URL
    RewriteCond %{HTTP:X-Requested-With}    !^XMLHttpRequest$
    RewriteCond %{THE_REQUEST}              ^[^/]*/index.php [NC]
    RewriteRule ^index.php(.*)$            $1 [R=301,NS,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search