[WORKING 100%] PHP CORS error 'Access-Control-Allow-Origin' missing - Enable CORS Laravel, CPanel

You can fix CORS issue easily by following below three steps. 

Step 1:

install CORS middleware 

As mentioned here , 

The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration. If you want to have a global overview of CORS workflow.

Step 2:

Cors class must be created under app\Http\Middleware directory upon completing Step 1. And replace entire class with following code.


<?php
// namespace
namespace App\Http\Middleware;
// use
use Closure;
use Illuminate\Http\Request;
class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers', '*'); } }

Step 3:

Finally, Just add the following in .htaccess file (yourapplicationhosting/public under public directory).


<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    RewriteEngine On
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
Keep in Mind:
Remove Access-Control-Allow-Origin code from other .htaccess file which is located in your hosting / root directory. Otherwise you will get "Multiple CORS header 'Access-Control-Allow-Origin' not allowed" error

 

That's it and good to go. 

This is how we can fix the the Cors Issue


Summary:

Enable CORS on Cpanel hosted applicaton