laravel怎么設置跨域(兩種方法)

在前后端分離的項目中,前端請求后端接口時可能會遇到跨域的問題。其中,一個典型的場景是:前端項目運行在 http://localhost:8080,而后端項目運行在 http://localhost:8000,這時候就需要設置跨域。

在 Laravel 中,要設置跨域可以采用以下兩種方法。

  1. 中間件方式

先創建一個中間件 CorsMiddleware:

php artisan make:middleware CorsMiddleware

在 CorsMiddleware 中處理跨域:

<?php  namespace AppHttpMiddleware;  use Closure;  class CorsMiddleware {     public function handle($request, Closure $next)     {         $origin = $request->header('Origin') ?: '*';          header('Access-Control-Allow-Origin: ' . $origin);         header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');         header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');          return $next($request);     } }

該中間件會在 Http/Kernel.php 中的 $middleware 數組中注冊:

protected $middleware = [     // ...     AppHttpMiddlewareCorsMiddleware::class, ];

這時候 Laravel 將在響應頭中添加 Access-Control-Allow-Origin 等跨域相關的信息。

  1. Laravel-cors 擴展包

其實,Laravel 社區已經有許多開源擴展包可以用來處理跨域問題。比如,laravel-cors,它提供了一些配置項來設置跨域請求。

首先,安裝擴展包:

composer require barryvdh/laravel-cors

接著,在 config/app.php 中的 providers 數組中注冊服務提供者:

'providers' => [     // ...     BarryvdhCorsServiceProvider::class, ],

最后,發布配置文件:

php artisan vendor:publish --provider="BarryvdhCorsServiceProvider"

這時候,可以在 config/cors.php 中配置跨域請求:

return [      /*     |--------------------------------------------------------------------------     | Laravel CORS Options     |--------------------------------------------------------------------------     |     | The allowed_methods and allowed_headers options are case-insensitive.     |     */      'allowed_origins' => ['*'],      'allowed_origins_patterns' => [],      'allowed_headers' => ['*'],      'allowed_methods' => ['*'],      'exposed_headers' => [],      'max_age' => 0,      'supports_credentials' => false,  ];

按照需求進行相應的配置即可。

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享