Friday, October 27, 2023

Laravel CORS Middleware Setting

 What is CORS?

CORS stands for Cross-origin resource sharing. The concept is related to the same origin policy which all browsers implement. In a nutshell, this policy says that a web site may not perform web requests to a different web site, or to be precise, “origin” (scheme, hostname, port number). CORS is a mechanism that can relax such restrictions. While the browser enforces restriction, CORS must be implemented on the server side to let the browser know that it may relax the restrictions.


Let’s get started

Using your Terminal or command prompt, navigate to your project’s root directory and run the following artisan command:

php artisan make:middleware corsMiddleware

That command will create a middleware file in /app/Http/Middleware, now open the new file in editor and add the following code

<?phpnamespace App\Http\Middleware;use Closure;class corsMiddleware{/*** @param $request* @param Closure $next* @return mixed*/public function handle($request, Closure $next) {
         $response = $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', '*')
        ->header('Access-Control-Allow-Credentials', true)
        ->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
        ->header('Accept', 'application/json');
        return $response;
}}

Now go to /app/Http/Kernel.php, add the following line to the $middleware array:

\App\Http\Middleware\corsMiddleware::class

After that add the bellow line to the $routeMiddleware array inside the same directory /app/Http/Kernel.php

‘cors’ => \App\Http\Middleware\corsMiddleware::class,

No comments:

Post a Comment