Skip to content

Instantly share code, notes, and snippets.

@drewjoh
Created June 13, 2016 22:47
Show Gist options
  • Select an option

  • Save drewjoh/43ba206c1cde9ace35de154a5c84fc6d to your computer and use it in GitHub Desktop.

Select an option

Save drewjoh/43ba206c1cde9ace35de154a5c84fc6d to your computer and use it in GitHub Desktop.
Laravel CORS Middleware

CORS stands for Cross-Origin Resource Sharing an is a specification that allow modern browsers to request (and receive) data from a domain other than the one serving the page that made the request.

You're building a site with cool cross domain features, and then you try to make a XHR request, you see the following message in your browser’s console:

XMLHttpRequest cannot load http://site123.local. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://site.local' is therefore not allowed access. The response had HTTP status code 500.

This means your server is not sending back to the client the headers that allow CORS:

1.Access-Control-Allow-Origin 2.Access-Control-Allow-Methods

So we'll make a Laravel Middleware to fix this. (You could also add the proper headers at the Ngnix level).

Create new middleware:

php artisan make:middleware Cors

Then follow the file examples in this gist to make it happen.

See http://enable-cors.org/ for more information.

<?php // /app/Http/Middleware/Cors.php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
<?php // /app/Http/Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'cors' => \App\Http\Middleware\Cors::class, // <<< add this line
];
<?php
Route::get('', ['middleware' => 'cors', function() {
return 'You did it!';
}]);
@ubiratanlima
Copy link
Copy Markdown

Caso ainda esteja com dificuldades, pode serguir esse aqui... funciona bem, muito simples de configurar tambem.
Lembrando que no Cors, se voce quiser todos basta colocar ['*'], caso contrario é só informar a origem.

https://github.com/barryvdh/laravel-cors

@adahox
Copy link
Copy Markdown

adahox commented Sep 5, 2018

Funcionou perfeitamente!!! parabéns e obrigado.

@gomesiagooo
Copy link
Copy Markdown

A documentação mostra como colocar urls na exceção do csrf.
https://laravel.com/docs/csrf#csrf-excluding-uris

@gilsonviana
Copy link
Copy Markdown

O example parece nao funcionar no Laravel versao 5.8

@NKmelnikov
Copy link
Copy Markdown

A documentação mostra como colocar urls na exceção do csrf.
https://laravel.com/docs/csrf#csrf-excluding-uris

Thanks. Your approach helped me

@Cardoso-topdev
Copy link
Copy Markdown

Thanks for your detailed documentation.
It helped me to solve the cors error.
:)

@cryptiswap-admin
Copy link
Copy Markdown

cryptiswap-admin commented May 9, 2022

Are you able to only add 2 domains without using a wildcard "*" to allow all domains? I mean, what's the point of CORS if you are allowing all origins?

@forwells
Copy link
Copy Markdown

forwells commented Nov 8, 2024

Laravel 系统自身携带的handlecors中间件仅处理同端口的跨域请求, 如果你使用spa 你猜这种方式是否会继续工作?哈哈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment