From 62d6c58f85cd8896d0ce56ad9fb8e3c58be885ca Mon Sep 17 00:00:00 2001 From: hgc Date: Mon, 23 Dec 2024 19:57:49 +0800 Subject: [PATCH] =?UTF-8?q?fix=20=E8=B7=A8=E5=9F=9F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/middleware/Cros.php | 26 ++++++++++++++++++++++++++ config/middleware.php | 12 ++++++++++-- config/route.php | 12 ++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 app/middleware/Cros.php diff --git a/app/middleware/Cros.php b/app/middleware/Cros.php new file mode 100644 index 0000000..2a1fa70 --- /dev/null +++ b/app/middleware/Cros.php @@ -0,0 +1,26 @@ +method() == 'OPTIONS' ? response('') : $handler($request); + + // 给响应添加跨域相关的http头 + $response->withHeaders([ + 'Access-Control-Allow-Credentials' => 'true', + 'Access-Control-Allow-Origin' => $request->header('origin', '*'), + 'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'), + 'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'), + ]); + + return $response; + } +} \ No newline at end of file diff --git a/config/middleware.php b/config/middleware.php index 8e964ed..905458e 100644 --- a/config/middleware.php +++ b/config/middleware.php @@ -6,10 +6,18 @@ * For full copyright and license information, please see the MIT-LICENSE.txt * Redistributions of files must retain the above copyright notice. * - * @author walkor + * @author walkorp * @copyright walkor * @link http://www.workerman.net/ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ -return []; \ No newline at end of file + +return [ + // 全局中间件 + '' => [ + // ... 这里省略其它中间件 +// app\middleware\Cros::class, + ] + +]; \ No newline at end of file diff --git a/config/route.php b/config/route.php index edff486..fbd75b0 100644 --- a/config/route.php +++ b/config/route.php @@ -16,6 +16,7 @@ use app\controller\AdController; use app\controller\OAuthController; use app\controller\GoogleAdsController; +use support\Request; use Webman\Route; @@ -115,6 +116,17 @@ Route::group('/googleads', function () { }); }); +Route::fallback(function (Request $request) { + $response = strtoupper($request->method()) === 'OPTIONS' ? response('', 204) : response('', 404); + $response->withHeaders([ + 'Access-Control-Allow-Credentials' => 'true', + 'Access-Control-Allow-Origin' => "*", + 'Access-Control-Allow-Methods' => '*', + 'Access-Control-Allow-Headers' => '*', + ]); + return $response; +}); +