API Development, CORS, Laravel, Lumen, PHP

Lumen and CORS

Lumen and CORS. I’m sure i’m not the only one who hates seeing this when I write an API for whatever reason and I get this when I try to make requests!!!

I’d be going through the what and the how to solve (without installing external packages).

 

What is  “No Access-Control-Allow-Origin header is present on the requested resource” ?

This is an error you get when you at Origin (or domain) A tries to gain access to resources at Origin B. Origin A has to make a cross-origin HTTP request when its requests a resource from Origin B. This is called Cross-Origin Resource Sharing (CORS).

Okay, now you know what CORS is. Why is it preventing you from making requests when your Lumen API is still hosted locally?

Well, this is because the requesting origin is different from the API’s origin since they are running on different ports.  It doesn’t matter that they are on the same machine/hostname.

 

Now I know what the problem is, How do I fix it ?

Its simple! Just enable CORS on the server by adding the Access-Control-Allow-Origin header.

Where and how do you add this header?

  • Go to app\Http\Middleware in your Lumen app and create a new middleware. You can call it anything you like 🙂
  • You will need to add headers to the handle function of your new middleware. Your code should look like this:
namespace App\Http\Middleware;

use Closure;

class NameOfYourMiddleware
{
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => 'https://url_of_your_app_requesting_resource',
            'Access-Control-Allow-Methods'     => 'POST, GET, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

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

        return $response;
    }
}

You can also use ‘*’ as the value for ‘Access-Control-Allow-Origin’ as opposed to the url of the app requesting the resource. Note that when you do this, you give EVERY origin access to your resource (and you might not want that).

Once you have enabled CORS on your server, you can move on to the third and final step.

  • Go to bootstrap\app.php and register your new middleware. Your code should look like this:
$app->middleware([
    ... //you may have other middlewares registered
    App\Http\Middleware\NameOfYourMiddleware::class
]);

You’re done!

 

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *