|
|
@@ -1,51 +1,35 @@
|
|
|
<?php
|
|
|
-declare(strict_types=1);
|
|
|
+
|
|
|
namespace app\api\middleware;
|
|
|
|
|
|
-use Closure;
|
|
|
-use think\Config;
|
|
|
-use think\Request;
|
|
|
use think\Response;
|
|
|
|
|
|
-class AllowCrossDomain{
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
- /**
|
|
|
- * 允许跨域请求
|
|
|
- * @access public
|
|
|
- * @param Request $request
|
|
|
- * @param Closure $next
|
|
|
- * @param array $header
|
|
|
- * @return Response
|
|
|
- */
|
|
|
- public function handle(Request $request, Closure $next, array $header = []): Response
|
|
|
+class AllowCrossDomain
|
|
|
+{
|
|
|
+ public function handle($request, \Closure $next)
|
|
|
{
|
|
|
-
|
|
|
- // 从配置文件中获取允许的域名列表
|
|
|
- // 允许的源
|
|
|
- // 从.env文件读取配置并转换为数组
|
|
|
- $allowedOriginsStr = env('CORS_ALLOWED_ORIGINS', '');
|
|
|
- $allowedOrigins = explode(',', $allowedOriginsStr);
|
|
|
- $origin = $request->header('Origin');
|
|
|
+ // 处理预检请求
|
|
|
+ if ($request->isOptions()) {
|
|
|
+ return response('', 204)
|
|
|
+ ->header([
|
|
|
+ 'Access-Control-Allow-Origin' => '*', // 或具体域名
|
|
|
+ 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
|
|
|
+ 'Access-Control-Allow-Headers' => 'Content-Type,Authorization,Accept-Language',
|
|
|
+ 'Access-Control-Max-Age' => '86400',
|
|
|
+ ]);
|
|
|
+ }
|
|
|
|
|
|
- dump($origin);die;
|
|
|
- if (in_array($origin, $allowedOrigins)) {
|
|
|
- header('Access-Control-Allow-Origin: '. $origin);
|
|
|
- } else {
|
|
|
+ // 继续后续请求
|
|
|
+ $response = $next($request);
|
|
|
|
|
|
- // 处理不允许的来源,例如返回403错误
|
|
|
- return response()->code(403)->data(['message' => 'Forbidden']);
|
|
|
- }
|
|
|
- header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
|
|
- header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
|
|
|
- header('Access-Control-Allow-Credentials: true');
|
|
|
- if ($request->method() === 'OPTIONS') {
|
|
|
- return response()->code(204);
|
|
|
- }
|
|
|
-
|
|
|
-
|
|
|
+ // 设置跨域头
|
|
|
+ $response->header([
|
|
|
+ 'Access-Control-Allow-Origin' => '*', // 或 'https://sz-test-3.hxiaoju.top'
|
|
|
+ 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
|
|
|
+ 'Access-Control-Allow-Headers' => 'Content-Type,Authorization,Accept-Language',
|
|
|
+ 'Access-Control-Max-Age' => '86400',
|
|
|
+ ]);
|
|
|
|
|
|
- return $next($request)->header($header);
|
|
|
+ return $response;
|
|
|
}
|
|
|
}
|