I've looked for some ways to enable cors on laravel 5.1 specifically, I have found some libs like:
https://github.com/neomerx/cors-illuminate
https://github.com/barryvdh/laravel-cors
but none of them has a implementation tutorial specifically to Laravel 5.1, I tried to config but It doesn't work.
If someone already implemented CORS on laravel 5.1 I would be grateful for the help...
The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin:https://hogehoge.com .
Cross-Origin Resource Sharing (CORS for short) provides a mechanism through which browsers and server-side applications can agree on requests that are allowed or restricted. From version 7, the Laravel framework comes with first-party support for sending CORS headers using Middlewares.
Your API resource has a CORS policy which restricts what domains may access the resource. The error you're getting is telling you that the resource does not have a CORS header allowing access from the calling domain. You need to set the CORS policy to whitelist your domain: http://localhost:3000 .
Here is my CORS middleware:
<?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; } }
To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:
protected $routeMiddleware = [ //other middlewares 'cors' => 'App\Http\Middleware\CORS', ];
Then you can use it in your routes
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
use App\Http\Controllers\ExampleController; Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
I always use an easy method. Just add below lines to \public\index.php
file. You don't have to use a middleware I think.
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With