| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?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
- {
-
- // 从配置文件中获取允许的域名列表
- // 允许的源
- // 从.env文件读取配置并转换为数组
- $allowedOriginsStr = env('CORS_ALLOWED_ORIGINS', '');
- $allowedOrigins = explode(',', $allowedOriginsStr);
- $origin = $request->header('Origin');
- dump($origin);die;
- if (in_array($origin, $allowedOrigins)) {
- header('Access-Control-Allow-Origin: '. $origin);
- } else {
- // 处理不允许的来源,例如返回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);
- }
-
-
- return $next($request)->header($header);
- }
- }
|