AllowCrossDomain.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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-Origin' =>'*'
  23. // 'Access-Control-Allow-Headers' => '*',
  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. }