方法一
在app>Http>Middleware添加
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
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;
// return $next($request);
}
}
方法二
使用fruitcake/laravel-cors:Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
安装fruitcake/laravel-cors
composer require fruitcake/laravel-cors
全局使用(对于所有路由)
在app/Http/Kernel.php
中$middleware
添加
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
在config/cors.php
中添加
'paths' => ['api/*'],
如果要精确设置请求白名单,则必须将白名单包含进allowed_methods所对应的数组
Note: If you are explicitly whitelisting headers, you must include Origin or requests will fail to be recognized as CORS.
<?php
return [
/*
* You can enable CORS for 1 or multiple paths.
* Example: ['api/*']
*/
'paths' => [],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins.
*/
'allowed_origins' => ['*'],
/*
* Matches the request origin with, similar to `Request::is()`
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header.
*/
'exposed_headers' => false,
/*
* Sets the Access-Control-Max-Age response header.
*/
'max_age' => false,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
];
allowed_origins
allowed_headers
和 allowed_methods
可以设置成[’*’] 来允许所有值
Note: When using custom headers, like X-Auth-Token or
X-Requested-With, you must set the allowed_headers to include those headers. You can also set it to [’*’] to allow all custom headers.
Note: Because of http method overriding in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.
参考:
https://packagist.org/packages/fruitcake/laravel-cors
https://segmentfault.com/a/1190000021891566