Ajax - Cross-Origin Request Blocked in Larave 5?

By Hardik Savani | March 30, 2016 | | 17174 Viewer | Category : Laravel jQuery AngularJS Ajax


Share this post:



When i was working on my laravel 5 project and i was making backend API, i created successfully but when front-end developer call API which i made. It's return like: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://learnl52.hd/register. (Reason: CORS header 'Access-Control-Allow-Origin' missing)." and i did try to how to solve this issue. I did also try with jquery and angularjs from backend but result nothing always.

At last i did found how to solve this issue, i made one middleware that allows to Cross-Origin Request in your laravel application. so let's create new middleware :

Create Middleware

php artisan make:middleware CORS

On now you can check on Middleware(app/Http/Middleware) directory, you can find CORS.php file and put bellow code on that file.

app/Http/Middleware/CORS.php

namespace App\Http\Middleware;

use Closure;

class CORS

{

public function handle($request, Closure $next)

{

header('Access-Control-Allow-Origin: *');


$headers = [

'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',

'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'

];

if($request->getMethod() == "OPTIONS") {

return Response::make('OK', 200, $headers);

}


$response = $next($request);

foreach($headers as $key => $value)

$response->header($key, $value);

return $response;

}

}

Ok, now register new created middleware on Kernel.php(app/Http/Kernel.php) file and append following line.

app/Http/Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel

{

...

...

protected $routeMiddleware = [

...

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

];

}

Now we are ready to use 'cors' middleware on route file so, use following way:

app/Http/routes.php

Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {

Route::post('register', 'APIController@register');

Route::post('login', 'APIController@login');

});