AllowCrossDomain.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare (strict_types=1);
  3. namespace app\middleware;
  4. use Closure;
  5. use think\Config;
  6. use think\Request;
  7. use think\Response;
  8. /**
  9. * 跨域中间件
  10. * Class AllowCrossDomain
  11. * @package app\middleware
  12. */
  13. class AllowCrossDomain
  14. {
  15. protected $cookieDomain;
  16. // header头配置
  17. protected $header = [
  18. "Access-Control-Allow-Origin" => "*",//注意修改这里填写你的前端的域名
  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,
  23. ,content-type,ignore',
  24. ];
  25. /**
  26. * AllowCrossDomain constructor.
  27. * @param Config $config
  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 $header
  39. * @return Response
  40. */
  41. public function handle($request, Closure $next, ?array $header = [])
  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. }