废话不多说,直接上代码
创建一个中间件 CrossMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Response;
class CrossMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$IlluminateResponse = 'Illuminate\Http\Response';
$SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
$headers = [
'Access-Control-Allow-Origin' => '*',//可以控制访问的域名
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN',
'Access-Control-Allow-Credentials'=>true
];
if ($response instanceof $IlluminateResponse) {
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
if ($response instanceof $SymfonyResopnse) {
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
}
return $response;
}
}
因为想作用在api的路由中,所以可以在Kernel.php 中设置
protected $middlewareGroups = [
....
....
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\CrossMiddleware::class
],
];
也可以放在 $middleware 中,这样就全局有效了!