CORS.php 874 B

123456789101112131415161718192021222324252627
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class CORS
  5. {
  6. public function handle($request, Closure $next)
  7. {
  8. $origin = $request->header('origin');
  9. if(empty($origin)){
  10. $referer = $request->header('referer');
  11. if(!empty($referer)&&preg_match("/^((https|http):\/\/)?([^\/]+)/i", $referer, $matches)){
  12. $origin = $matches[0];
  13. }
  14. }
  15. $response = $next($request);
  16. $response->header('Access-Control-Allow-Origin', trim($origin, '/'));
  17. $response->header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  18. $response->header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  19. $response->header('Access-Control-Allow-Credentials', 'true');
  20. $response->header('Access-Control-Max-Age', 10080);
  21. return $response;
  22. }
  23. }