在 Laravel 9 之前出現錯誤時:
Access to XMLHttpRequest at 'http://localhost:8000/demo' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我必須安裝fruitcake/laravel-cors(https://www.positronx.io/how-to-enable-cors-in-laravel/)。
在 Laravel 9 中我找到了資訊:
「將 Laravel CORS 整合到框架中 Dries Vints 將 Fruitcake/laravel-cors 套件遷移到 Laravel 框架中: 主要原因是我們除了消除骨架的另一個依賴之外,還希望消除我們所依賴的循環依賴。 代碼的所有學分均歸@fruitcake 的@barryvdh 所有。感謝您長期維護該軟體包! 」。
如何在新的 Laravel 中為 url: api/list 和 api/profiles 建立 cors?
P粉1762037812023-11-02 09:41:55
在您的 app/Http/Kernel.php
中檢查 CORS 中間件是否存在:
protected $middleware = [ ... \Illuminate\Http\Middleware\HandleCors::class, ... ];
然後開啟您的config/cors.php
。它的工作原理與 fruitcake/laravel-cors
完全相同:
['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];