laravel7.0 Laravel-cors 開發包實現跨域
阿新 • • 發佈:2020-10-22
Laravel 7.0 跨域解決方案
注意:laravel 7.0 是預設帶有 fruitcake/laravel-cors 開發包
1. 根據自己所需自定義 header 頭 config/cors.php
<?php return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => ['*'], 'allowed_headers' => ['*'], 'exposed_headers' => false, 'max_age' => false, 'supports_credentials' => false, ];
2. 新增 HandleCors 中介軟體到 app/Http/Kernel.php 允許所有 api 跨域,
protected $middleware = [
...
\Fruitcake\Cors\HandleCors::class,
];
在 $routeMiddleware 屬性中新增:
protected $routeMiddleware = [
...
'cors' => \Fruitcake\Cors\HandleCors::class,
]
在 config/app.php 中到 providers 裡新增服務提供者:
'providers' => [ ... Fruitcake\Cors\CorsServiceProvider::class, ]
在 routes/api.php 中新增路由以及 cors 中介軟體:
Route::middleware('cors')->group(function (){
Route::get('article', function(){
return response()->json('跨域成功!',200);
});
});
laravel 7.0 之前解決跨域方案
第一步:建立中介軟體
php artisan make:middleware EnableCrossRequestMiddleware
第二步:編輯中介軟體 app/Http/Middleware/EnableCrossRequestMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware{
public function handle($request, Closure $next)
{
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE'); // 允許請求的型別
header('Access-Control-Allow-Credentials: true'); // 設定是否允許傳送 cookies
header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods'); // 設定允許自定義請求頭的欄位
return $next($request);
}
}
第三步:註冊中介軟體(全域性)app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
...
\App\Http\Middleware\EnableCrossRequestMiddleware::class,
];