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 'https://laravel-api.com/api/call' from origin 'https://angular-app.com' 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

<?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','UserController@getData')->middleware('CORS');

This should work and solve the issue.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments