laravel7.0 Laravel-cors 開發包實現跨域


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,
    ];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM