Laravel プロジェクトにおける CORS(クロスオリジン)リクエストの問題
Q&A
Cloud Run に Laravel プロジェクトをデプロイする際、CSS や JS などの静的ファイルの読み込みで CORS(クロスオリジン)エラーが発生していますてください。
発生している問題・エラー
自分で試したこと
ルートファイル web.php に CORS ヘッダーを手動で追加しました。
Route::get('/build/assets/{path}', function ($path) {
$fullPath = public_path("build/assets/{$path}");
if (!file_exists($fullPath)) {
abort(404);
}
return Response::file($fullPath, [
'Content-Type' => mime_content_type($fullPath),
'Access-Control-Allow-Origin' => 'https://my-server-domin',
'Access-Control-Allow-Methods' => 'GET, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization',
]);
})->where('path', '.*');
さらに、OPTIONS プリフライトリクエストの処理も追加しました
Route::options('/build/assets/{file}', function () {
return response('', 204)
->header('Access-Control-Allow-Origin', 'https://my-server-domin')
->header('Access-Control-Allow-Methods', 'GET, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
})->where('file', '.*');
Cloud Run の起動コマンドは以下のように設定しました
CMD ["php", "artisan", "serve", "--host=0.0.0.0", "--port=8080"]
※ Laravel のバージョンは 12.12 を使用しています。