firebaseHostingへデプロイしたアプリから、firebaseFunctionへリクエストを送り、apiを利用したいです。
解決したいこと
firebaseHostingへデプロイしたアプリから、firebaseFunctionへリクエストを送り、apiを利用したいです。
404エラーを解消し、正常にapiを呼び出したいです。ルーティングの箇所に誤りがあれば指摘お願いします。
発生している問題・エラー
出ているエラーメッセージを入力
polyfills.ea3cb635cad86c66.js:1
POST https://us-central1-musictomovie-af3d1.cloudfunctions.net/api/hello 404
z @ polyfills.ea3cb635cad86c66.js:1
・
・
・
6260.eeadfbd059add584.js:1 POSTリクエストが失敗しました。 Lt {headers: ee, status: 404, statusText: 'OK', url: 'https://us-central1-musictomovie-af3d1.cloudfunctions.net/api/hello', ok: false, …}
または、問題・エラーが起きている画像をここにドラッグアンドドロップ
該当するソースコード
■クライアントサイド
// postリクエストのテスト用
sendPostRequest() {
const formData = {
audio: this.audioFile,
image: this.imageFile,
};
this.http.post<any>('https://us-central1-musictomovie-af3d1.cloudfunctions.net/api/hello',formData).subscribe(
(data) => {
this.response = data.message;
console.log('サーバーからの応答:', data); // コンソールにも表示(確認用)
},
(error) => {
console.error('POSTリクエストが失敗しました。', error);
}
);
}
■サーバーサイド
●index.ts:
import * as functions from "firebase-functions";
import app from "./app";
// Express アプリケーションを Firebase Functions にラップします
const api = functions.https.onRequest(app);
// Firebase Functions のエントリーポイントとしてエクスポートします
export { api };
●app.ts:
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import mediaRoutes from './routes/media.routes';
import helloRoutes from './routes/hello.routes';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
// CORS設定(手動で設定)
app.use(cors({
origin: ['https://us-central1-musictomovie-af3d1.cloudfunctions.net',
'https://us-central1-musictomovie-af3d1.cloudfunctions.net/api/',
'https://us-central1-musictomovie-af3d1.cloudfunctions.net/api/hello',
'https://musictomovie-af3d1.web.app'],
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
}));
// エンドポイントのルーティング
app.use('/api', mediaRoutes);
app.use('/api', helloRoutes);
// テスト用のログを追加
console.log("mediaRoutesのルーティングは以下のパスで設定されています:");
console.log("/api/media/createVideo");
console.log("/api/hello");
// app.listen(PORT, () => {
// console.log(`Server is running on port ${PORT}`);
// });
export default app;
●hello.routes.ts:
import express, { Router, Request, Response } from 'express';
const router: Router = express.Router();
console.log("hello.routes.tsが呼び出されました")
// "hello world"をクライアントに返すエンドポイント(POSTリクエスト)
router.post('/hello', (req: Request, res: Response) => {
try {
console.log("hello worldを返します")
res.json({ message: 'hello world' }); // JSON形式で応答を返す
} catch (error) {
console.error("エラーが発生しました:", error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
export default router;
### 自分で試したこと
クライアントサイドurl、サーバーサイドのルーティングをいろいろ変えてみましたが駄目でした。
ローカルで実行したときには問題なく動いていたんですが、index.tsを追加して実際にデプロイすると
エラーになってしまいました。
0 likes