AllowCrossDomain.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2021/4/9
  6. * Time: 17:51
  7. */
  8. declare (strict_types = 1);
  9. namespace app\middleware;
  10. use Closure;
  11. use think\Config;
  12. use think\Request;
  13. use think\Response;
  14. class AllowCrossDomain
  15. {
  16. protected $cookieDomain;
  17. // header头配置
  18. protected $header = [
  19. 'Access-Control-Allow-Credentials' => 'true',
  20. 'Access-Control-Max-Age' => 1800,
  21. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
  22. 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token',
  23. ];
  24. /**
  25. * AllowCrossDomain constructor.
  26. * @param Config $config
  27. */
  28. public function __construct(Config $config)
  29. {
  30. $this->cookieDomain = $config->get('cookie.domain', '');
  31. }
  32. /**
  33. * 允许跨域请求
  34. * @access public
  35. * @param Request $request
  36. * @param Closure $next
  37. * @param array $header
  38. * @return Response
  39. */
  40. public function handle($request, Closure $next, ?array $header = [])
  41. {
  42. $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
  43. if (!isset($header['Access-Control-Allow-Origin'])) {
  44. $origin = $request->header('origin');
  45. if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
  46. $header['Access-Control-Allow-Origin'] = $origin;
  47. } else {
  48. $header['Access-Control-Allow-Origin'] = '*';
  49. }
  50. }
  51. return $next($request)->header($header);
  52. }
  53. }