AllowCrossDomain.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. protected $cookieDomain;
  10. protected $header = [
  11. 'Access-Control-Allow-Credentials' => 'true',
  12. 'Access-Control-Max-Age' => 1800,
  13. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
  14. 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
  15. ];
  16. public function __construct(Config $config)
  17. {
  18. $this->cookieDomain = $config->get('cookie.domain', '');
  19. }
  20. /**
  21. * 允许跨域请求
  22. * @access public
  23. * @param Request $request
  24. * @param Closure $next
  25. * @param array $header
  26. * @return Response
  27. */
  28. public function handle(Request $request, Closure $next, array $header = []): Response
  29. {
  30. $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
  31. if (!isset($header['Access-Control-Allow-Origin'])) {
  32. $origin = $request->header('origin');
  33. if ($origin && ('' == $this->cookieDomain || str_contains($origin, $this->cookieDomain))) {
  34. $header['Access-Control-Allow-Origin'] = $origin;
  35. } else {
  36. $header['Access-Control-Allow-Origin'] = '*';
  37. }
  38. }
  39. return $next($request)->header($header);
  40. }
  41. }