2 回答

TA貢獻1808條經驗 獲得超4個贊
最簡單的解決方案 轉到 bootstrap 文件夾并打開 app.php 文件。然后只需在文件頂部添加這些行。應用程序.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
另一個解決方案:
php artisan make:middleware Cors
現在從 App\Http\Middleware 文件夾中打開 Cors.php 并用以下代碼替換 handle() 函數:
Cors.php
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, Authorizations');
}
最后,從 App\Http 文件夾中打開 Kernel.php,將以下行添加到 $middleware 數組中:
protected $middleware = [
...
\App\Http\Middleware\Cors::class,
];
現在運行應用程序并從任何地方調用 API。

TA貢獻1895條經驗 獲得超7個贊
需要 composer.json 中的fruitcake/laravel-cors 包并更新您的依賴項:
composer require fruitcake/laravel-cors
全球使用
要允許所有路由使用 CORS,請在app/Http/Kernel.php類的 $middleware 屬性中添加 HandleCors 中間件:
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
配置
php artisan vendor:publish --tag="cors"
現在更新配置以定義要在其上運行 CORS 服務的路徑(請參閱下面的配置):
配置/cors.php
'paths' => ['api/*'],
更多細節https://github.com/fruitcake/laravel-cors
- 2 回答
- 0 關注
- 185 瀏覽
添加回答
舉報