使用 laravel-cors 实现 Laravel 的跨域配置[我是大白,我是猿]

一、需求
一个项目需要进行前端跨域,不适用 jsonp。

因此需要进行 cors 的设置。

最开始的时候,我使用的是路由中间件的方式,但是发现中间件不起作用。

// 路由中间件
public function handle($request, Closure $next)
{

$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'false');
return $response;

}
因此后面直接使用了 laravel-cors 的库来实现。

laravel-cors 库 地址:

https://github.com/barryvdh/laravel-cors
二、使用
安装:
composer require barryvdh/laravel-cors
我使用的是 laravel 5.6 如果低于 5.5 版本需要手动进行注册服务:

位于:config/app.php,添加下面代码

Barryvdh\Cors\ServiceProvider::class,
全局使用:
如果作为全局使用的中间件,则直接加入到 middleware 中即可:

修改 app/Http/kernel.php 文件:

protected $middleware = [
// …
\Barryvdh\Cors\HandleCors::class,
];
中间件组使用
如果只是在中间件组中使用,则加入相应的中间件组就OK

protected $middlewareGroups = [
‘web’ => [
// …
],

'api' => [
    // ...
    \Barryvdh\Cors\HandleCors::class,
],

];
配置选项
导出配置:

php artisan vendor:publish --provider=“Barryvdh\Cors\ServiceProvider”
配置的基本内容:

return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array(’’)
| to accept any value.
|
/
‘supportsCredentials’ => false,
‘allowedOrigins’ => [’
’],
‘allowedHeaders’ => [‘Content-Type’, ‘X-Requested-With’],
‘allowedMethods’ => [’
’], // ex: [‘GET’, ‘POST’, ‘PUT’, ‘DELETE’]
‘exposedHeaders’ => [],
‘maxAge’ => 0,
]

生活步步是坎坷,笑到最后是大哥。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值