AllowOrigin.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | A3Mall
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: xzncit <158373108@qq.com>
  8. // +----------------------------------------------------------------------
  9. namespace mall\middleware;
  10. use Closure;
  11. use think\Config;
  12. use think\Request;
  13. use think\Response;
  14. class AllowOrigin {
  15. protected $cookieDomain;
  16. protected $headers = [
  17. 'Access-Control-Allow-Credentials' => 'true',
  18. 'Access-Control-Allow-Origin' => '*',
  19. 'Access-Control-Allow-Headers' => 'Auth-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
  20. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS',
  21. 'Access-Control-Max-Age' => '1728000'
  22. ];
  23. public function __construct(Config $config){
  24. $this->cookieDomain = $config->get('cookie.domain', '');
  25. }
  26. /**
  27. * @param Request $request
  28. * @param Closure $next
  29. * @return Response
  30. */
  31. public function handle(Request $request, Closure $next){
  32. $header = $this->headers;
  33. $origin = $request->header('origin');
  34. if (!empty($origin) && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
  35. $header['Access-Control-Allow-Origin'] = $origin;
  36. } else {
  37. $header['Access-Control-Allow-Origin'] = '*';
  38. //$header['Access-Control-Allow-Origin'] = 'http://localhost:8080';
  39. }
  40. if ($request->method(true) == 'OPTIONS') {
  41. return Response::create()->code(204)->header($header);
  42. }
  43. return $next($request)->header($header);
  44. }
  45. }