Loading

Handle CORS error in Lumen

Handle CORS error in Lumen

Cross-Origin Resource Sharing or CORS is a mechanism or technique which is built into all modern web browsers for security reason. It basically blocks all the HTTP requests which are not coming from the same origin or domain where your API or backend exists.

In a simple statement: If the requests are not coming from the same domain or origin, simply ignore.

Let understood practically: Suppose we have opened a website from Domain1 in our browser and asking for a file or data from Domain2. Now our web browser makes a call to Domain2. On Domain2, if there is a policy to accept HTTP requests only from Domain2 and ignore all requests from other domains, then Domain1 request will fail with CORS error.

Access to XMLHttpRequest at 'http://localhost:4400/page1' from origin 'http://localhost:4200' has been blocked by CORS policy.

Create a CORS middleware class: Create a new PHP file on your app\Http\Middleware folder and name it. Let say, the filename is CorsMiddleware.php in this example and copy the codes below:

<?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;
    }
}

Now, if we look carefully to the above code, Access-Control-Allow-Origin is set to * and it tells the browser to accept request from any sources (*).

'Access-Control-Allow-Origin' => '*'

We can also restrict it easily by specifying the domain name in place of *.

Register the CORS middleware class: To enable the CORS policy we need to register it by adding the below code on the bootstrap/app.php file.

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

Finally, if we run it in our browser, sometimes we would see in the browser console network tab that a hidden HTTP OPTIONS request is sent (not always) before our actual request and it because our browser tries to check whether the browser is allowed to perform the action.

Related Articles