使用 Node.js (第 1 代) 建立及部署 HTTP Cloud Run 函式

本指南將逐步說明如何使用 Node.js 執行階段編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:

  • 可從標準 HTTP 要求叫用的 HTTP 函式。
  • 用於處理 Cloud 基礎架構事件的事件驅動函式,例如 Pub/Sub 主題上的訊息,或 Cloud Storage bucket 的變更。

此範例說明如何建立簡單的 HTTP 函式。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. 安裝並初始化 gcloud CLI
  9. 更新並安裝 gcloud 元件:
    gcloud components update
  10. 準備開發環境。

    前往 Node.js 設定指南

  11. 建立函式

    1. 在本機系統上為函式程式碼建立目錄:

      Linux 或 Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. helloworld 目錄中建立含有以下內容的 index.js 檔案:

      const functions = require('@google-cloud/functions-framework');
      const escapeHtml = require('escape-html');
      
      /**
       * Responds to an HTTP request using data from the request body parsed according
       * to the "content-type" header.
       *
       * @param {Object} req Cloud Function request context.
       * @param {Object} res Cloud Function response context.
       */
      functions.http('helloHttp', (req, res) => {
        res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
      });

      此範例函式採用在 HTTP 要求中提供的名稱,並傳回問候語;如未提供名稱,則會傳回「Hello World!」。

    指定依附元件

    Node.js 中的依附元件會儲存在 package.json 檔案中。您可以手動建立此檔案,也可以使用 npm 指令建立。

    • 如要使用 npm 建立 package.json 依附元件檔案,請執行下列指令:

      npm init
      npm install c8 gaxios mocha sinon supertest wait-port --save-dev
      npm install @google-cloud/functions-framework escape-html
      
    • 如要手動建構 package.json 檔案,請在 helloworld 目錄中建立 package.json 檔案,並加入下列內容:

      {
        "name": "nodejs-docs-samples-functions-hello-world-http",
        "version": "0.0.1",
        "private": true,
        "license": "Apache-2.0",
        "author": "Google Inc.",
        "repository": {
          "type": "git",
          "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
        },
        "engines": {
          "node": ">=16.0.0"
        },
        "scripts": {
          "unit-test": "c8 mocha -p -j 2 test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=6000 --exit",
          "system-test": "c8 mocha -p -j 2 test/*system*test.js --timeout=600000 --exit",
          "all-test": "npm run unit-test && npm run system-test",
          "test": "npm -- run unit-test"
        },
        "dependencies": {
          "@google-cloud/functions-framework": "^3.1.0",
          "escape-html": "^1.0.3"
        },
        "devDependencies": {
          "c8": "^10.0.0",
          "gaxios": "^6.0.0",
          "mocha": "^10.0.0",
          "sinon": "^18.0.0",
          "supertest": "^7.0.0",
          "wait-port": "^1.0.4"
        }
      }
      

    部署函式

    如要使用 HTTP 觸發條件部署函式,請在 helloworld 目錄中執行下列指令:

    gcloud functions deploy helloHttp --no-gen2 --runtime nodejs22 --trigger-http --allow-unauthenticated
    

    透過 --allow-unauthenticated 旗標,您無須驗證即可使用函式。如果需要驗證,請略過該旗標。

    測試函式

    1. 函式完成部署時,請記下 httpsTrigger.url 屬性,或使用下列指令找到該屬性:

      gcloud functions describe helloHttp
      

      內容應類似這樣:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
    2. 使用瀏覽器造訪此網址,應該會看到「Hello World!」訊息。

      請嘗試透過 HTTP 要求傳遞名稱,例如使用下列網址:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

      您應該會看到「Hello NAME!」訊息。

    查看記錄

    您可以使用 Google Cloud CLI,以及在 Cloud Logging UI 中,查看 Cloud Run 函式的記錄。

    使用指令列工具

    如要透過 gcloud CLI 查看函式的記錄,請使用 logs read 指令,再加上函式的名稱:

    gcloud functions logs read helloHttp

    輸出內容應會如下所示:

    LEVEL  NAME       EXECUTION_ID  TIME_UTC                 LOG
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:25.983  Function execution started
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:26.001  Function execution took 19 ms, finished with status code: 200

    使用 Logging 資訊主頁

    您也可以在Google Cloud 控制台查看 Cloud Run 函式的記錄。