AllowCrossDomain.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\middleware;
  4. use Closure;
  5. use think\Config;
  6. use think\Request;
  7. use think\Response;
  8. class AllowCrossDomain{
  9. /**
  10. * 允许跨域请求
  11. * @access public
  12. * @param Request $request
  13. * @param Closure $next
  14. * @param array $header
  15. * @return Response
  16. */
  17. public function handle(Request $request, Closure $next, array $header = []): Response
  18. {
  19. // 从配置文件中获取允许的域名列表
  20. // 允许的源
  21. // 从.env文件读取配置并转换为数组
  22. $allowedOriginsStr = env('CORS_ALLOWED_ORIGINS', '');
  23. $allowedOrigins = explode(',', $allowedOriginsStr);
  24. $origin = $request->header('Origin');
  25. dump($origin);die;
  26. if (in_array($origin, $allowedOrigins)) {
  27. header('Access-Control-Allow-Origin: '. $origin);
  28. } else {
  29. // 处理不允许的来源,例如返回403错误
  30. return response()->code(403)->data(['message' => 'Forbidden']);
  31. }
  32. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  33. header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  34. header('Access-Control-Allow-Credentials: true');
  35. if ($request->method() === 'OPTIONS') {
  36. return response()->code(204);
  37. }
  38. return $next($request)->header($header);
  39. }
  40. }