AllowCrossDomain.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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,content-type,ignore,token',//如果有新增header字段,在这里添加
  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. }