Hello guys, welcome back to another article of KDJ Guru Blog. Today, with this article, I came up with a solution to a problem that I got a few minutes ago. As I say every day, this is the best time I’m spending for my learning stuff with my office work. However, I have the whole 24/7 to do my learning curve. By the way, While I’m learning the lumen framework for my company project, I got a CORS issue.

CORS simply refers to Cross-Origin Resource Sharing. CORS is a method that uses HTTP calls to let a browser on a domain gain access to resources on a distinct origin. Anyways, I don’t need to say a lot about this thing, If you need more, just google.

1. Make a CORS middleware

Make a file called ‘CorsMiddleware.php’ in the path ‘app\Http\Middleware’. Then paste the following code there. You don’t have to change anything.

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

Then Register the above middleware on your bootstrap/app.php file. You have no uncommenting here. Just find the commented example middleware and paste the following code below that.

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

After all, you can send Axios request as you wish. Lumen is a better solution for all of us to write APIs easily. I will bring more solutions as soon as possible. I can say it surely, I got many issues. Especially, I’m trying to bring you an article about the authentication part ASAP.

Please stay with us and stay at home during corona time. Have a nice day!

Write A Comment