v2board/app/Http/Middleware/CORS.php

28 lines
904 B
PHP
Raw Permalink Normal View History

2019-10-29 15:33:36 +08:00
<?php
namespace App\Http\Middleware;
use Closure;
class CORS
{
public function handle($request, Closure $next)
{
$origin = $request->header('origin');
2020-01-11 13:36:52 +08:00
if (empty($origin)) {
2019-10-29 15:33:36 +08:00
$referer = $request->header('referer');
2020-01-11 13:36:52 +08:00
if (!empty($referer) && preg_match("/^((https|http):\/\/)?([^\/]+)/i", $referer, $matches)) {
2019-10-29 15:33:36 +08:00
$origin = $matches[0];
}
}
$response = $next($request);
$response->header('Access-Control-Allow-Origin', trim($origin, '/'));
2022-07-11 14:48:35 +08:00
$response->header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,HEAD');
$response->header('Access-Control-Allow-Headers', 'Origin,Content-Type,Accept,Authorization,X-Request-With');
2019-10-29 15:33:36 +08:00
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Max-Age', 10080);
2020-01-11 13:36:52 +08:00
2019-10-29 15:33:36 +08:00
return $response;
}
2020-01-11 13:36:52 +08:00
}