扩展包地址:barryvdh/laravel-cors
(1)安装,项目根目录
composer require barryvdh/laravel-cors
Laravel 5.4 及以下版本需要手动在 config/app.php 中注册服务提供者:
Barryvdh\Cors\ServiceProvider::class,
(2)使用
全局使用的中间件,在app/Http/kernel.php 文件:
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class,
];
特定路由中应用 CORS
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
(3)配置
自定义配置,laravel-cors 扩展包的配置文件发布到 config 目录下:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
以下是该配置文件默认配置值(config/cors.php):
eturn [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
以上步骤操作完,发起请求会报403错误,具体没找原因,知道小伙伴,可留言。
在gitHub上面找到了问题:
我使用的是 laravel 5.7 api + dingo + laravel-cors not work,需要在 config/app.php 中操注册服务提供者:
'providers' => [
Barryvdh\Cors\ServiceProvider::class
]
所以上面提到的laravel5.4<=版本需要添加,这个需要根据具体情况而定。
1,新建一个中间件
php artisan make:middleware EnableCrossRequestMiddleware
2.CrossRequestMiddleware.php
?php
namespace App\Http\Middleware;
use Closure;
class CrossRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
$allow_origin = [
'http://localhost:8000',
];
if (in_array($origin, $allow_origin)) {
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS,DELETE');
$response->header('Access-Control-Allow-Credentials', 'true');
}
return $response;
}
}
3,全局使用,注册该中间件
protected $middleware = [
// more
App\Http\Middleware\CrossRequestMiddleware::class,
];