快速入门:在 Azure 中从命令行创建 JavaScript 函数Quickstart: Create a JavaScript function in Azure from the command line

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的 JavaScript 函数。In this article, you use command-line tools to create a JavaScript function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

完成本快速入门会从你的 Azure 帐户中扣取最多几美分的费用。Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

本文还提供了基于 Visual Studio 代码的版本There is also a Visual Studio Code-based version of this article.

配置本地环境Configure your local environment

在开始之前,必须满足以下条件:Before you begin, you must have the following:

先决条件检查Prerequisite check

验证你的先决条件,这取决于你是使用 Azure CLI 还是使用 Azure PowerShell 创建 Azure 资源:Verify your prerequisites, which depend on whether you are using Azure CLI or Azure PowerShell for creating Azure resources:

  • 在终端或命令窗口中,运行 func --version 以检查 Azure Functions Core Tools 的版本是否为 3.x。In a terminal or command window, run func --version to check that the Azure Functions Core Tools are version 3.x.

  • 运行 az --version 以检查 Azure CLI 版本是否为 2.4 或更高版本。Run az --version to check that the Azure CLI version is 2.4 or later.

  • 运行 az login 登录到 Azure 并验证活动订阅。Run az login to sign in to Azure and verify an active subscription.

创建本地函数项目Create a local function project

在 Azure Functions 中,有一个函数项目是一个或多个单独函数(每个函数响应特定的触发器)的容器。In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. 项目中的所有函数共享相同的本地和宿主配置。All functions in a project share the same local and hosting configurations. 在本部分,你将创建包含单个函数的函数项目。In this section, you create a function project that contains a single function.

  1. 按如下所示运行 func init 命令,在名为 LocalFunctionProj 的文件夹中创建使用指定运行时的函数项目:Run the func init command, as follows, to create a functions project in a folder named LocalFunctionProj with the specified runtime:

    func init LocalFunctionProj --javascript
    
  2. 导航到项目文件夹:Navigate into the project folder:

    cd LocalFunctionProj
    

    此文件夹包含项目的各个文件,其中包括名为 local.settings.jsonhost.json 的配置文件。This folder contains various files for the project, including configurations files named local.settings.json and host.json. 由于 local.settings.json 可以包含从 Azure 下载的机密,因此,默认情况下,该文件会从 .gitignore 文件的源代码管理中排除。Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

  3. 使用以下命令将一个函数添加到项目,其中,--name 参数是该函数 (HttpExample) 的唯一名称,--template 参数指定该函数的触发器 (HTTP)。Add a function to your project by using the following command, where the --name argument is the unique name of your function (HttpExample) and the --template argument specifies the function's trigger (HTTP).

    func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
    

    func new 创建一个与函数名称匹配的、包含项目所选语言适用的代码文件的子文件夹,以及一个名为 function.json 的配置文件。func new creates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json.

(可选)检查文件内容(Optional) Examine the file contents

如果需要,可以跳到在本地运行函数并稍后再检查文件内容。If desired, you can skip to Run the function locally and examine the file contents later.

index.jsindex.js

index.js 导出一个根据 function.json 中的配置触发的函数。index.js exports a function that's triggered according to the configuration in function.json.

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

对于 HTTP 触发器,该函数将接收 function.json 中定义的变量 req 中的请求数据。For an HTTP trigger, the function receives request data in the variable req as defined in function.json. function.json 中定义为 $return 的返回对象是响应。The return object, defined as $return in function.json, is the response. 要了解详细信息,请参阅 Azure Functions HTTP 触发器和绑定To learn more, see Azure Functions HTTP triggers and bindings.

function.jsonfunction.json

function.json 是一个配置文件,其中定义了函数的输入和输出 bindings,包括触发器类型。function.json is a configuration file that defines the input and output bindings for the function, including the trigger type.

{
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}

每个绑定都需要一个方向、类型和唯一的名称。Each binding requires a direction, a type, and a unique name. HTTP 触发器具有类型为 httpTrigger 的输入绑定和类型为 http 的输出绑定。The HTTP trigger has an input binding of type httpTrigger and output binding of type http.

在本地运行函数Run the function locally

  1. 通过从 LocalFunctionProj 文件夹启动本地 Azure Functions 运行时主机来运行函数:Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

    func start
    

    在输出的末尾,应显示以下行:Toward the end of the output, the following lines should appear:

     ...
    
     Now listening on: http://0.0.0.0:7071
     Application started. Press Ctrl+C to shut down.
    
     Http Functions:
    
             HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
     ...
    
     

    备注

    如果 HttpExample 未按如上所示出现,则可能是在项目的根文件夹外启动了主机。If HttpExample doesn't appear as shown above, you likely started the host from outside the root folder of the project. 在这种情况下,请按 Ctrl+C 停止主机,导航到项目的根文件夹,然后重新运行上一命令。In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

  2. 将此输出中 HttpExample 函数的 URL 复制到浏览器,并追加查询字符串 ?name=<YOUR_NAME>,使完整 URL 类似于 http://localhost:7071/api/HttpExample?name=FunctionsCopy the URL of your HttpExample function from this output to a browser and append the query string ?name=<YOUR_NAME>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. 浏览器应会显示类似于 Hello Functions 的消息:The browser should display a message like Hello Functions:

    在浏览器中本地运行函数后的结果

  3. 当你发出请求时,启动项目时所在的终端还会显示日志输出。The terminal in which you started your project also shows log output as you make requests.

  4. 完成后,请按 Ctrl+C 并选择 y 以停止函数主机 。When you're done, use Ctrl+C and choose y to stop the functions host.

创建函数的支持性 Azure 资源Create supporting Azure resources for your function

在将函数代码部署到 Azure 之前,需要创建三个资源:Before you can deploy your function code to Azure, you need to create three resources:

  • 一个资源组:相关资源的逻辑容器。A resource group, which is a logical container for related resources.
  • 一个存储帐户:维护有关项目的状态和其他信息。A Storage account, which maintains state and other information about your projects.
  • 一个函数应用:提供用于执行函数代码的环境。A function app, which provides the environment for executing your function code. 函数应用映射到本地函数项目,可让你将函数分组为一个逻辑单元,以便更轻松地管理、部署和共享资源。A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

使用以下命令创建这些项。Use the following commands to create these items. 支持 Azure CLI 和 PowerShell。Both Azure CLI and PowerShell are supported.

  1. 请登录到 Azure(如果尚未这样做):If you haven't done so already, sign in to Azure:

    az login
    

    使用 az login 命令登录到 Azure 帐户。The az login command signs you into your Azure account.

  2. chinanorth 区域中创建名为 AzureFunctionsQuickstart-rg 的资源组:Create a resource group named AzureFunctionsQuickstart-rg in the chinanorth region:

    az group create --name AzureFunctionsQuickstart-rg --location chinanorth
    

    az group create 命令可创建资源组。The az group create command creates a resource group. 通常,你会在从 az account list-locations 命令返回的、离你近的某个可用区域中创建资源组和资源。You generally create your resource group and resources in a region near you, using an available region returned from the az account list-locations command.

  3. 在资源组和区域中创建常规用途存储帐户:Create a general-purpose storage account in your resource group and region:

    az storage account create --name <STORAGE_NAME> --location chinanorth --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS
    

    az storage account create 命令可创建存储帐户。The az storage account create command creates the storage account.

    在上一个示例中,将 <STORAGE_NAME> 替换为适合你且在 Azure 存储中唯一的名称。In the previous example, replace <STORAGE_NAME> with a name that is appropriate to you and unique in Azure Storage. 名称只能包含 3 到 24 个数字和小写字母字符。Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS 指定 Functions 支持的常规用途帐户。Standard_LRS specifies a general-purpose account, which is supported by Functions.

  1. 在 Azure 中创建函数应用:Create the function app in Azure:

    az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location chinanorth2 --runtime node --runtime-version 12 --functions-version 3 --name <APP_NAME> --storage-account <STORAGE_NAME>
    

    az functionapp create 命令可在 Azure 中创建函数应用。The az functionapp create command creates the function app in Azure. 如果使用的是 Node.js 10,请同时将 --runtime-version 更改为 10If you're using Node.js 10, also change --runtime-version to 10.

    在上一个示例中,请将 <STORAGE_NAME> 替换为在上一步骤中使用的帐户的名称,并将 <APP_NAME> 替换为适合自己的全局唯一名称。In the previous example, replace <STORAGE_NAME> with the name of the account you used in the previous step, and replace <APP_NAME> with a globally unique name appropriate to you. <APP_NAME> 也是函数应用的默认 DNS 域。The <APP_NAME> is also the default DNS domain for the function app.

    此命令将创建一个函数应用,该应用在 Azure Functions 消耗计划下指定的语言运行时中运行,根据本教程产生的用量,此操作是免费的。This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. 该命令还会在同一资源组中预配关联的 Azure Application Insights 实例,可以使用它来监视函数应用和查看日志。The command also provisions an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. 有关详细信息,请参阅监视 Azure FunctionsFor more information, see Monitor Azure Functions. 该实例在激活之前不会产生费用。The instance incurs no costs until you activate it.

将函数项目部署到 AzureDeploy the function project to Azure

在 Azure 中成功创建函数应用后,便可以使用 func azure functionapp publish 命令部署本地函数项目。After you've successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish command.

在以下示例中,请将 <APP_NAME> 替换为你的应用的名称。In the following example, replace <APP_NAME> with the name of your app.

func azure functionapp publish <APP_NAME>

publish 命令显示类似于以下输出的结果(为简洁起见,示例中的结果已截断):The publish command shows results similar to the following output (truncated for simplicity):

...

Getting site publishing info...
Creating archive for current directory...
Performing remote build for functions project.

...

Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
        Invoke url: https://msdocs-azurefunctions-qs.chinacloudsites.cn/api/httpexample

在 Azure 上调用函数Invoke the function on Azure

由于函数使用 HTTP 触发器,因此,可以通过在浏览器中或使用 curl 等工具,向此函数的 URL 发出 HTTP 请求来调用它。Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.

将 publish 命令的输出中显示的完整“调用 URL”复制到浏览器的地址栏,并追加查询参数 &name=FunctionsCopy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter &name=Functions. 浏览器显示的输出应与本地运行函数时显示的输出类似。The browser should display similar output as when you ran the function locally.

运行以下命令以查看准实时流式处理日志Run the following command to view near real-time streaming logs:

func azure functionapp logstream <APP_NAME> 

在单独的终端窗口或浏览器中,再次调用远程函数。In a separate terminal window or in the browser, call the remote function again. 终端中显示了 Azure 中函数执行的详细日志。A verbose log of the function execution in Azure is shown in the terminal.

清理资源Clean up resources

若要继续执行下一步并添加 Azure 存储队列输出绑定,请保留所有资源,以备将来使用。If you continue to the next step and add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.

否则,请使用以下命令删除资源组及其包含的所有资源,以免产生额外的费用。Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

az group delete --name AzureFunctionsQuickstart-rg

后续步骤Next steps