Angular and Laravel CORS Access-Control-Allow-Origin Issues

  167 views   1 month ago Laravel AngularJS

I was woking on a Laravel API application for Angular. When I was working locally everything was working fine. But when i deploy the Laravel and Angular applications to the live server, I was getting CORS errors in Angular in browser console.

Access to XMLHttpRequest at '' from origin '' 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.

This issue can be solved by adding appropriate headers in Laravel application. You can set this by adding Middleware in these routes. Here is the middleware file at /app/Http/Middleware/CORS.php


namespace App\Http\Middleware;

use Closure;

class CORS
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $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', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');

Add the middleware to $routeMiddleware variable in app/Http/Kernel.php file.

protected $routeMiddleware = [
   'CORS' => \App\Http\Middleware\CORS::class,

And add the middleware to route.

Route::get('/users/get-data','[email protected]')->middleware('CORS');

This should work and solve the issue.

I hope it will help you to solve the issue.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]