AllowOriginMiddleware.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\middleware;
  12. use app\Request;
  13. use think\exception\HttpResponseException;
  14. use think\facade\Config;
  15. use think\Response;
  16. /**
  17. * 跨域中间件
  18. * Class AllowOriginMiddleware
  19. * @package app\http\middleware
  20. */
  21. class AllowOriginMiddleware extends BaseMiddleware
  22. {
  23. /**
  24. * header头
  25. * @var array
  26. */
  27. protected $header = [
  28. 'Access-Control-Allow-Origin' => '*',
  29. 'Access-Control-Allow-Headers' => 'LatLon, 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
  30. //'Access-Control-Allow-Headers' => '*',
  31. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
  32. 'Access-Control-Max-Age' => '1728000'
  33. ];
  34. public function before(Request $request)
  35. {
  36. $cookieDomain = Config::get('cookie.domain', '');
  37. $origin = $request->header('origin');
  38. $lonlat = trim($request->header('LatLon'));
  39. $request->macro('lonlat', function () use ($lonlat) {
  40. return $lonlat;
  41. });
  42. if ($origin && $cookieDomain && strpos($origin, $cookieDomain))
  43. $this->header['Access-Control-Allow-Origin'] = $origin;
  44. if ($request->method(true) == 'OPTIONS') {
  45. throw new HttpResponseException(Response::create()->code(200)->header($this->header));
  46. }
  47. }
  48. public function after(Response $response)
  49. {
  50. $response->header($this->header);
  51. }
  52. }