How to enable CORS in Laravel?

前端 未结 3 1054
无人及你
无人及你 2020-12-20 16:57

I am in Laravel 5.8 - I kept getting this CORS issue

\"\"

I\'ve tried

php artisan make:mi         


        
相关标签:
3条回答
  • 2020-12-20 17:46

    Try laravel-cors package that allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

    0 讨论(0)
  • 2020-12-20 17:55

    Add below to you .htaccess (just add to the destination site and origin site)

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Max-Age "1000"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
    

    Hope it saves someone time, happy coding!!!

    0 讨论(0)
  • 2020-12-20 18:02

    First solution

    Try to set the CORS middleware as a global middleware.

    the handle function in the CORS middleware:

     public function handle($request, Closure $next)
     {
      return $next($request)
       ->header('Access-Control-Allow-Origin', '*')
       ->header('Access-Control-Allow-Methods', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
       ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
     }
    

    to add this middleware globally, go to App\Http\Kernel, and add this line in the $middleware array:

    \App\Http\Middleware\Cors::class,
    

    Second solution

    you can also add this code in the bootstrap/app.php

    header('Access-Control-Allow-Origin', '*');
    header('Access-Control-Allow-Methods', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
    header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    

    hope it works!

    0 讨论(0)
提交回复
热议问题