AllowOriginMiddleware.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace app\common\middleware;
  3. use app\Request;
  4. use think\exception\HttpResponseException;
  5. use think\facade\Config;
  6. use think\Response;
  7. /**
  8. * 跨域中间件
  9. * Class AllowOriginMiddleware
  10. * @package app\http\middleware
  11. */
  12. class AllowOriginMiddleware extends BaseMiddleware
  13. {
  14. /**
  15. * header头
  16. * @var array
  17. */
  18. protected $header = [
  19. 'Access-Control-Allow-Origin' => '*',
  20. 'Access-Control-Allow-Headers' => 'X-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,Form-type,Referer,Connection,Content-Length,Host,Origin,Authorization,Authori-zation,Accept,Accept-Encoding',//,Host,Origin,Authorization,Authori-zation,Accept,Accept-Encoding
  21. //'Access-Control-Allow-Headers' => '*',
  22. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
  23. 'Access-Control-Max-Age' => '1728000'
  24. ];
  25. public function before(Request $request)
  26. {
  27. $cookieDomain = Config::get('cookie.domain', '');
  28. $origin = $request->header('origin');
  29. if ($origin && $cookieDomain && strpos($origin, $cookieDomain))
  30. $this->header['Access-Control-Allow-Origin'] = $origin;
  31. if ($request->method(true) == 'OPTIONS') {
  32. throw new HttpResponseException(Response::create()->code(200)->header($this->header));
  33. }
  34. }
  35. public function after(Response $response)
  36. {
  37. $response->header($this->header);
  38. }
  39. }