AllowCrossDomain.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\middleware;
  13. use Closure;
  14. use think\Config;
  15. use think\Request;
  16. use think\Response;
  17. /**
  18. * 跨域请求支持
  19. */
  20. class AllowCrossDomain
  21. {
  22. protected mixed $cookieDomain;
  23. protected array $header = [
  24. 'Access-Control-Allow-Credentials' => 'true',
  25. 'Access-Control-Max-Age' => 1800,
  26. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
  27. 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
  28. ];
  29. public function __construct(Config $config)
  30. {
  31. $this->cookieDomain = $config->get('cookie.domain', '');
  32. }
  33. /**
  34. * 允许跨域请求
  35. * @access public
  36. * @param Request $request
  37. * @param Closure $next
  38. * @param array|null $header
  39. * @return Response
  40. */
  41. public function handle(Request $request, Closure $next, ?array $header = []): Response
  42. {
  43. $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
  44. if (!isset($header['Access-Control-Allow-Origin'])) {
  45. $origin = $request->header('origin');
  46. if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
  47. $header['Access-Control-Allow-Origin'] = $origin;
  48. } else {
  49. $header['Access-Control-Allow-Origin'] = '*';
  50. }
  51. }
  52. return $next($request)->header($header);
  53. }
  54. }