1
votes

I am running laravel lumen php frameowrk 5.5.2 on localhost\8080 on my machine.I am running angular4 frontend locally on localhost\4200. When I run my application, I am able to connect to some Laravel apis through angular and get the data and also I can make changes to those apis. But when i try to connect to some other apis in Laravel through my front-end, I am getting this error in the browser console "Access to XMLHttpRequest at 'http://localhost:8080/ABC' from origin 'http://localhost:4200' 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 referred to this link and made respective changes at the Laravel backend server code as mentioned by them: https://gist.github.com/danharper/06d2386f0b826b669552#file-usage-md

But then, when i connect to Laravel apis, through angular, now I get this error: "Access to XMLHttpRequest at 'http://localhost:8080/ABC' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

Also, do I have to make any changes to the angular front end code? I cannot move forward because of this CORS blocking...Any help would be greatly appreciated.

This is my CorsMiddleware.php file in Laravel:

use Closure;

class CorsMiddleware {

public function handle($request, Closure $next)
{

    $response = $next($request);
    $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, 
    PATCH, DELETE');
    $response->header('Access-Control-Allow-Headers', $request- 
    >header('Access-Control-Request-Headers'));
    $response->header('Access-Control-Allow-Origin', '*');
    return $response;    
}

}

This is my CatchAllOptionsRequestsProvider.php file in Laravel:

/** * If the incoming request is an OPTIONS request * we will register a handler for the requested route */

class CatchAllOptionsRequestsProvider extends ServiceProvider {

public function register()
{
    $request = app('request');

    if ($request->isMethod('OPTIONS'))
    {
       app()->options($request->path(), function() { return response('', 
       200); 
    });
}

}

This is my app.php file where i register my provider and Cors middleware:

$app->register(App\Providers\CatchAllOptionsRequestsProvider::class);

$app->routeMiddleware(['auth' => App\Http\Middleware\Authenticate::class,]);

$app->middleware([App\Http\Middleware\CorsMiddleware::class]);

1

1 Answers

3
votes

Do the following:

1. create the middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

2. Add the middleware to the app/Http/kernel.php (for laravel)

protected $middleware  = [
//...... other middlewares
\App\Http\Middleware\CorsMiddleware::class
];

for lumen do this in bootstrap/app.php

 $app->middleware([
      App\Http\Middleware\CorsMiddleware::class
 ]);

DONE!!