Friday, February 5, 2016

How to use CORS requests in Laravel 5 with middleware

CORS requests in Laravel 5 with middleware:

For this we have to firstly create a middleware with name CORS and write the following code in it.

<?php

namespace App\Http\Middleware;

use Closure;


class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

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


Now go to the app/Http/kernel.php & add this line in $routeMiddleware

'cors' => \App\Http\Middleware\CORS::class,

Now in route.php we can use is like this



Route::group(['middleware' => 'cors'], function () {
    get('/script', 'ScriptController@getDetail');
    get('/response', 'ScriptController@postDetail');
});


Thanks

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. If you are using Laravel 5.5 Check this tutorial for fixing Laravel access-control-allow-origin error. You don't need to perform any special thing at angular js side. Just make few changes in Laravel as suggested in the tutorial.
    http://www.laravelinterviewquestions.com/2017/12/cross-origin-request-blocked-error-laravel.html
    Thanks
    Happy Coding !!!

    ReplyDelete