AllowCrossDomain.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace app\api\middleware;
  3. use think\Response;
  4. class AllowCrossDomain
  5. {
  6. public function handle($request, \Closure $next)
  7. {
  8. // 处理预检请求
  9. if ($request->isOptions()) {
  10. return response('', 204)
  11. ->header([
  12. 'Access-Control-Allow-Origin' => '*', // 或具体域名
  13. 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
  14. 'Access-Control-Allow-Headers' => 'Content-Type,Authorization,Accept-Language,token',
  15. 'Access-Control-Max-Age' => '86400',
  16. ]);
  17. }
  18. // 继续后续请求
  19. $response = $next($request);
  20. // 设置跨域头
  21. $response->header([
  22. 'Access-Control-Allow-Origin' => '*', // 或 'https://sz-test-3.hxiaoju.top'
  23. 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
  24. 'Access-Control-Allow-Headers' => 'Content-Type,Authorization,Accept-Language,token',
  25. 'Access-Control-Max-Age' => '86400',
  26. ]);
  27. return $response;
  28. }
  29. }