Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS in lumen

Tags:

cors

api

lumen

I have API developed using lumen. I can get request using postman. But when request using Jquery.ajax it is not working. So I need to know how to enable CORS in lumen API.

like image 735
Ishan Fernando Avatar asked Apr 06 '16 10:04

Ishan Fernando


People also ask

How do you allow CORS in lumens?

Now you have to go into bootstrap\app. php and place or replace following code. $app->middleware([ App\Http\Middleware\CorsMiddleware::class ]); Thats it!!

How do I enable CORS access?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.

What is CORS and how do you enable it?

CORS stands for Cross Origin Resource Sharing. It is a HTTP-header based mechanism which enables the server to allow or restrict access from any other origins. A protocol, domain name, port or scheme requesting a URL which is different from the current page address depicts a cross-origin request.


1 Answers

Consider creating a CorsMiddleware.php file with the following code. Find detail here.

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

After saving it in your middleware folder, enable it by adding it to your bootstap/app.php file, on the list of you middleware like this

$app->middleware([
    ...
    App\Http\Middleware\CorsMiddleware::class // Add this

]);

I hope it helps.

like image 51
The Oracle Avatar answered Sep 24 '22 15:09

The Oracle