快速入门:使用 Node.js 创建和部署 HTTP Cloud Functions 函数

使用 Node.js 创建和部署 HTTP Cloud Functions 函数

本指南将引导您完成使用 Node.js 运行时编写 Cloud Functions 函数的过程。Cloud Functions 函数有两种类型:

  • HTTP 函数,通过标准 HTTP 请求调用。
  • 事件驱动型函数,用于处理来自云基础设施的事件,例如 Pub/Sub 主题中收到消息或 Cloud Storage 存储桶发生更改。

本指南中的示例演示了如何创建简单的 HTTP 函数。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Cloud Functions and Cloud Build API。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Cloud Functions and Cloud Build API。

    启用 API

  8. 安装并初始化 gcloud CLI
  9. 更新并安装 gcloud 组件:
    gcloud components update
  10. 准备开发环境。

    转到 Node.js 设置指南

创建一个函数

  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": "^8.0.0",
        "gaxios": "^6.0.0",
        "mocha": "^10.0.0",
        "sinon": "^16.0.0",
        "supertest": "^6.0.0",
        "wait-port": "^1.0.4"
      }
    }
    

部署该函数

如需使用 HTTP 触发器部署该函数,请在 helloworld 目录中运行以下命令:

gcloud functions deploy helloHttp --runtime nodejs20 --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 界面查看 Cloud Functions 函数的日志。

使用命令行工具

如需使用 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 Functions 函数的日志。