簡體   English   中英

本地模擬器 Firebase 雲 Function 無法獲取和 404

[英]Local Emulator Firebase Cloud Function Cannot Get and 404

我希望能夠使用模擬器在本地觸發 Firebase Cloud Function。 但是,function 始終返回404 Not Found作為狀態碼,並且Cannot Get作為響應正文。 對於上下文,function 在本地部署(即您可以在 UI 上看到它),但是當您點擊它時,它會返回上述錯誤。

它部署到這個端點http://localhost:5001/project/region/health我正在運行的命令是firebase emulators:start --only functions

// app.ts
import * as express from 'express';
import * as functions from 'firebase-functions';
import { router as healthRouter } from './api/utils/router';

const healthApp = express();

healthApp.use('/health', healthRouter);

export = {
  health: functions.region('northamerica-northeast1').https.onRequest(healthApp),
};
// router.ts
import { Router } from 'express';
import { health } from './health';

export const router = Router();

router.get('/', health);
// health.ts
import type { Request, Response } from 'firebase-functions';
import * as functions from 'firebase-functions';

export const health = functions.https.onRequest(
  (req: Request, res: Response) => {
    res.status(200);
  }
);
// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "allowSyntheticDefaultImports": true
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

當您通過 Firebase Function 導出快速應用程序時,路徑將與導出的 function 名稱相關。 您將應用程序導出為 exports.health ,它將 function 的根路徑設置為 /health 並調用它,您將訪問http://localhost:5001/project/northamerica-northeast1/health

但是,因為您還為 /health 定義了一個路由處理程序(使用router.get("/health", healthRouter) ),所以您為 http://localhost:5001/project/northamerica-northeast1/health/health 添加了一個處理程序反而。

錯誤Cannot GET /被拋出,因為當您在 ttp://localhost:5001/project/northamerica-northeast1/health 調用 function 時,相對的 URL 設置為“/”,您尚未為其配置處理程序(使用 router.get("/", healthRouter))。

要修復上面的代碼,請將您的代碼更改為:

路由器.ts

router.get('/', health);

應用程序.ts

healthApp.use('/', healthRouter);

健康.ts

export const health = functions.https.onRequest(
  (req: Request, res: Response) => {
    res.send('Hello World!')
    res.status(200)
  }
);

這將返回status: 200Hello World! 的響應! . 此外,請確保在運行firebase emulators:start --only functions之前運行npm run build

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM