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; +}); +