Cors.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. class Cors
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
  12. * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
  13. */
  14. public function handle(Request $request, Closure $next)
  15. {
  16. $response = $next($request);
  17. $IlluminateResponse = 'Illuminate\Http\Response';
  18. $SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
  19. $headers = [
  20. 'Access-Control-Allow-Origin' => '*',
  21. 'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
  22. 'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers, X-CSRF-TOKEN'
  23. ];
  24. if ($response instanceof $IlluminateResponse) {
  25. foreach ($headers as $key => $value) {
  26. $response->header($key, $value);
  27. }
  28. return $response;
  29. }
  30. if ($response instanceof $SymfonyResopnse) {
  31. foreach ($headers as $key => $value) {
  32. $response->headers->set($key, $value);
  33. }
  34. return $response;
  35. }
  36. return $response;
  37. }
  38. }