How to Enable CORS on Lumen Framework API
Hello friends, in this article I am going to show you how to enable CORS on Lumen API Simply CORS is known as Cross Origin Resource Sharing. CORS is a way that makes use of HTTP requests to allow a browser on one origin(a domain) benefit access to sources on a specific origin. By default, a method called the Same-Origin policy is used to save your JavaScript code from making ajax requests to another domain. So consider you are building a website which has Vue.Js as frontend technology and Laravel/Lumen API as backend technology. Now when you try to make a API request to Laravel you might get an error on Cross Origin Resource Sharing. The error might be similar as below.
Generally, there is a simple solution for this. Some sites may tell you have to add lot of things such as headers, third party dependencies and much more. But Now I am gonna show you an easy way to solve this issue from Lumen API side. So we have to create a middleware for this. If you have no idea on middleware, I will simply describe about middleware.
Middleware
Basically, Middleware is a technique for filtering HTTP requests which coming into your app so that you can simply adjust HTTP Requests and Responses in a suitable way. Middleware acts as a bridge among a request and a response
Solution
Create a CORS middleware file at app\Http\Middleware
Create a new file called CorsMiddleware.php inside the app\Http\Middleware. Then copy and paste the following code.
<?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 register the created Middleware
Now you have to go into bootstrap\app.php and place or replace following code.
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
Thats it!! now you can send axios requests. If you have any problems please comment below.
Or check my latest posts.