In projects with separate front-end and back-end, cross-domain problems may be encountered when the front-end requests the back-end interface. Among them, a typical scenario is: the front-end project runs at http://localhost:8080, and the back-end project runs at http://localhost:8000. In this case, cross-domain settings need to be set.
In Laravel, you can use the following two methods to set up cross-domain.
First create a middleware CorsMiddleware:
php artisan make:middleware CorsMiddleware
Handle cross-domain in CorsMiddleware:
<?php namespace App\Http\Middleware; use Closure; class CorsMiddleware { public function handle($request, Closure $next) { $origin = $request->header('Origin') ?: '*'; header('Access-Control-Allow-Origin: ' . $origin); header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); return $next($request); } }
The The middleware will be registered in the $middleware array in Http/Kernel.php:
protected $middleware = [ // ... \App\Http\Middleware\CorsMiddleware::class, ];
At this time, Laravel will add cross-domain related information such as Access-Control-Allow-Origin in the response header.
In fact, the Laravel community already has many open source extension packages that can be used to handle cross-domain issues. For example, laravel-cors provides some configuration items to set up cross-domain requests.
First, install the extension package:
composer require barryvdh/laravel-cors
Then, register the service provider in the providers array in config/app.php:
'providers' => [ // ... Barryvdh\Cors\ServiceProvider::class, ],
Finally, publish the configuration file:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
At this time, you can configure cross-domain requests in config/cors.php:
return [ /* |-------------------------------------------------------------------------- | Laravel CORS Options |-------------------------------------------------------------------------- | | The allowed_methods and allowed_headers options are case-insensitive. | */ 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'allowed_methods' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
Configure accordingly as required.
The above are two methods for setting up cross-domain settings in Laravel. Just choose the one that suits you.
The above is the detailed content of How to set up cross-domain laravel (two methods). For more information, please follow other related articles on the PHP Chinese website!