教程:在 Azure 中生成 Node.js 和 MongoDB 应用Tutorial: Build a Node.js and MongoDB app in Azure

Azure 应用服务提供高度可缩放、自修补的 Web 托管服务。Azure App Service provides a highly scalable, self-patching web hosting service. 本教程演示如何在应用服务中创建 Node.js 应用,并将其连接至 MongoDB 数据库。This tutorial shows how to create a Node.js app in App Service and connect it to a MongoDB database. 完成本教程后,将获得一个在 Azure App Service 中运行的 MEAN(MongoDB、Express、AngularJS 和 Node.js)应用程序)。When you're done, you'll have a MEAN application (MongoDB, Express, AngularJS, and Node.js) running in Azure App Service. 为简单起见,示例应用程序使用了 MEAN.js web 框架For simplicity, the sample application uses the MEAN.js web framework.

在 Azure 应用服务中运行的 MEAN.js 应用

学习内容:What you'll learn:

  • 在 Azure 中创建 MongoDB 数据库Create a MongoDB database in Azure
  • 将 Node.js 应用连接到 MongoDBConnect a Node.js app to MongoDB
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 从 Azure 流式传输诊断日志Stream diagnostic logs from Azure
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

完成本教程:To complete this tutorial:

  1. 安装 GitInstall Git
  2. 安装 Node.js 和 NPMInstall Node.js and NPM
  3. 安装 BowerMEAN.js 所需的)Install Bower (required by MEAN.js)
  4. 安装 Gulp.js (MEAN.js 要求的)Install Gulp.js (required by MEAN.js)
  5. 安装并运行 MongoDB 社区版Install and run MongoDB Community Edition

测试本地 MongoDBTest local MongoDB

打开终端窗口并cd打开到bin MongoDB 安装的目录。Open the terminal window and cd to the bin directory of your MongoDB installation. 可使用此终端窗口运行本教程中的所有命令。You can use this terminal window to run all the commands in this tutorial.

在终端运行 mongo 以连接到本地 MongoDB 服务器。Run mongo in the terminal to connect to your local MongoDB server.

mongo

如果连接成功,那么 MongoDB 数据库已经开始运行。If your connection is successful, then your MongoDB database is already running. 如果连接不成功,那么请确保本地 MongoDB 数据库按安装 MongoDB 社区版中的步骤来启动。If not, make sure that your local MongoDB database is started by following the steps at Install MongoDB Community Edition. 通常,MongoDB 已安装,但是仍需要运行 mongod 来启动它。Often, MongoDB is installed, but you still need to start it by running mongod.

完成 MongoDB 数据库测试后,请在终端键入 Ctrl+CWhen you're done testing your MongoDB database, type Ctrl+C in the terminal.

创建本地 Node.js 应用Create local Node.js app

在此步骤中,将设置本地 Node.js 项目。In this step, you set up the local Node.js project.

克隆示例应用程序Clone the sample application

在终端窗口中,通过 cd 转到工作目录。In the terminal window, cd to a working directory.

运行下列命令,克隆示例存储库。Run the following command to clone the sample repository.

git clone https://github.com/Azure-Samples/meanjs.git

此示例存储库包含 MEAN.js 存储库的副本。This sample repository contains a copy of the MEAN.js repository. 它修改为在应用服务上运行(有关详细信息,请参阅 MEAN.js 存储库 README 文件)。It is modified to run on App Service (for more information, see the MEAN.js repository README file).

运行应用程序Run the application

运行以下命令以安装所需安装包并启动应用程序。Run the following commands to install the required packages and start the application.

cd meanjs
npm install
npm start

当应用完全加载后,会看见类似下方所示的消息:When the app is fully loaded, you see something similar to the following message:

--
MEAN.JS - Development Environment

Environment:     development
Server:          http://0.0.0.0:3000
Database:        mongodb://localhost/mean-dev
App version:     0.5.0
MEAN.JS version: 0.5.0
--

在浏览器中导航到 http://localhost:3000Navigate to http://localhost:3000 in a browser. 在顶部菜单点击“注册” 并创建一个测试用户。Click Sign Up in the top menu and create a test user.

MEAN.js 示例应用程序将用户数据存储在数据库中。The MEAN.js sample application stores user data in the database. 如果成功创建用户并登陆,那么应用会将数据写入本地 MongoDB 数据库。If you are successful at creating a user and signing in, then your app is writing data to the local MongoDB database.

MEAN.js 成功连接到 MongoDB

选择“管理员”>“管理文章” 以添加一些文章。Select Admin > Manage Articles to add some articles.

若要随时停止 Node.js,请在终端中按 Ctrl+CTo stop Node.js at any time, press Ctrl+C in the terminal.

Note

Node.js 快速入门提到需将 web.config 置于根应用目录中。The Node.js quickstart mentions the need for a web.config in the root app directory. 但在本教程中,此 web.config 文件会在你使用本地 Git 部署而非 ZIP 文件部署来部署文件时自动由应用服务生成。However, in this tutorial, this web.config file will be automatically generated by App Service when you deploy your files using local Git deployment instead of ZIP file deployment.

创建生产 MongoDBCreate production MongoDB

此步骤在 Azure 中创建一个 MongoDB 数据库。In this step, you create a MongoDB database in Azure. 应用部署到 Azure 后,它将使用该云数据库。When your app is deployed to Azure, it uses this cloud database.

对于 MongoDB,本教程使用了 Azure Cosmos DBFor MongoDB, this tutorial uses Azure Cosmos DB. Cosmos DB 支持 MongoDB 客户端连接。Cosmos DB supports MongoDB client connections.

创建资源组Create a resource group

资源组是在其中部署和管理 Azure 资源(例如 Web 应用、数据库和存储帐户)的逻辑容器。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed.

在 Azure CLI 中,使用 az group create 命令创建资源组。In the Azure CLI, create a resource group with the az group create command. 以下示例在“中国北部” 位置创建名为“myResourceGroup” 的资源组。The following example creates a resource group named myResourceGroup in the China North location. 要查看“免费”层中应用服务支持的所有位置,请运行 az appservice list-locations --sku FREE 命令。 To see all supported locations for App Service in Free tier, run the az appservice list-locations --sku FREE command.

az group create --name myResourceGroup --location "China North"

通常在附近的区域中创建资源组和资源。You generally create your resource group and the resources in a region near you.

此命令完成后,JSON 输出会显示资源组属性。When the command finishes, a JSON output shows you the resource group properties.

创建 Cosmos DB 帐户Create a Cosmos DB account

Note

在本教程中,在你自己的 Azure 订阅中创建 Azure Cosmos DB 数据库需付费。There is a cost to creating the Azure Cosmos DB databases in this tutorial in your own Azure subscription. 创建数据库以后,请在门户中导航到“连接字符串”,然后检索 Azure Cosmos DB 连接字符串,以便在本教程的后面使用。 Once the database is created, navigate to Connection String in the portal and retrieve your Azure Cosmos DB connection string for use later in the tutorial.

在 Azure CLI 中,使用 az cosmosdb create 命令创建 Cosmos DB 帐户。In Azure CLI, create a Cosmos DB account with the az cosmosdb create command.

在下面命令中,将 <cosmosdb_name> 占位符替换为一个唯一的 Cosmos DB 名称。In the following command, substitute a unique Cosmos DB name for the <cosmosdb_name> placeholder. 此名称将用作 Cosmos DB 终结点 https://<cosmosdb_name>.documents.azure.cn/ 的一部分,因此这个名称需要在 Azure 中的所有 Cosmos DB 帐户中具有唯一性。This name is used as the part of the Cosmos DB endpoint, https://<cosmosdb_name>.documents.azure.cn/, so the name needs to be unique across all Cosmos DB accounts in Azure. 此名称只能包含小写字母、数字以及连字符 (-),同时长度必须为 3 到 50 个字符。The name must contain only lowercase letters, numbers, and the hyphen (-) character, and must be between 3 and 50 characters long.

az cosmosdb create --name <cosmosdb_name> --resource-group myResourceGroup --kind MongoDB

--kind MongoDB 参数启用 MongoDB 客户端连接。The --kind MongoDB parameter enables MongoDB client connections.

创建 Cosmos DB 帐户后,Azure CLI 将显示类似于以下示例的信息:When the Cosmos DB account is created, the Azure CLI shows information similar to the following example:

{
  "consistencyPolicy":
  {
    "defaultConsistencyLevel": "Session",
    "maxIntervalInSeconds": 5,
    "maxStalenessPrefix": 100
  },
  "databaseAccountOfferType": "Standard",
  "documentEndpoint": "https://<cosmosdb_name>.documents.azure.cn:443/",
  "failoverPolicies": 
  ...
  < Output truncated for readability >
}

将应用连接到生产 MongoDBConnect app to production MongoDB

在此步骤中,使用 MongoDB 连接字符串将 MEAN.js 示例应用程序连接至刚创建的 Cosmos DB 数据库。In this step, you connect your MEAN.js sample application to the Cosmos DB database you just created, using a MongoDB connection string.

检索数据库键Retrieve the database key

若要连接到 Cosmos DB 数据库,需要数据库键。To connect to the Cosmos DB database, you need the database key. 在 Azure CLI 中,使用 az cosmosdb list-keys 命令检索主键。In Azure CLI, use the az cosmosdb list-keys command to retrieve the primary key.

az cosmosdb list-keys --name <cosmosdb_name> --resource-group myResourceGroup

Azure CLI 显示类似于以下示例的信息:The Azure CLI shows information similar to the following example:

{
  "primaryMasterKey": "RS4CmUwzGRASJPMoc0kiEvdnKmxyRILC9BWisAYh3Hq4zBYKr0XQiSE4pqx3UchBeO4QRCzUt1i7w0rOkitoJw==",
  "primaryReadonlyMasterKey": "HvitsjIYz8TwRmIuPEUAALRwqgKOzJUjW22wPL2U8zoMVhGvregBkBk9LdMTxqBgDETSq7obbwZtdeFY7hElTg==",
  "secondaryMasterKey": "Lu9aeZTiXU4PjuuyGBbvS1N9IRG3oegIrIh95U6VOstf9bJiiIpw3IfwSUgQWSEYM3VeEyrhHJ4rn3Ci0vuFqA==",
  "secondaryReadonlyMasterKey": "LpsCicpVZqHRy7qbMgrzbRKjbYCwCKPQRl0QpgReAOxMcggTvxJFA94fTi0oQ7xtxpftTJcXkjTirQ0pT7QFrQ=="
}

复制 primaryMasterKey 的值。 下一步骤需要用到此信息。You need this information in the next step.

在 Node.js 应用程序中配置连接字符串Configure the connection string in your Node.js application

在本地 MEAN.js 存储库的 config/env/ 文件夹中,创建名为 local-production.js 的文件。In your local MEAN.js repository, in the config/env/ folder, create a file named local-production.js. 默认情况下,通过配置 .gitignore 确保此文件位于存储库之外。By default, .gitignore is configured to keep this file out of the repository.

将以下代码复制到该文件中。Copy the following code into it. 请确保将两个 <cosmosdb_name> 占位符替换为 Cosmos DB 数据库名称,将 <primary_master_key> 占位符替换为在先前步骤中复制的键 。Be sure to replace the two <cosmosdb_name> placeholders with your Cosmos DB database name, and replace the <primary_master_key> placeholder with the key you copied in the previous step.

module.exports = {
  db: {
    uri: 'mongodb://<cosmosdb_name>:<primary_master_key>@<cosmosdb_name>.documents.azure.cn:10250/mean?ssl=true&sslverifycertificate=false'
  }
};

需要 ssl=true 选项,因为 Cosmos DB 需要 SSLThe ssl=true option is required because Cosmos DB requires SSL.

保存所做更改。Save your changes.

在生产模式下测试应用程序Test the application in production mode

运行以下命令缩减和捆绑用于生产环境的脚本。Run the following command to minify and bundle scripts for the production environment. 这一进程将生成生产环境所需的文件。This process generates the files needed by the production environment.

gulp prod

运行下列命令,以使用在 config/env/local-production.js 中配置的连接字符串。Run the following command to use the connection string you configured in config/env/local-production.js.

# Bash
NODE_ENV=production node server.js

# Windows PowerShell
$env:NODE_ENV = "production" 
node server.js

NODE_ENV=production 设置环境变量,用于指示 Node.js 在生产环境中运行。NODE_ENV=production sets the environment variable that tells Node.js to run in the production environment. node server.js 使用存储库根路径中的 server.js 启动 Node.js 服务器。node server.js starts the Node.js server with server.js in your repository root. 这就是 Node.js 应用程序在 Azure 中加载的方式。This is how your Node.js application is loaded in Azure.

在加载应用时请进行检查,确保它在生产环境中运行:When the app is loaded, check to make sure that it's running in the production environment:

--
MEAN.JS

Environment:     production
Server:          http://0.0.0.0:8443
Database:        mongodb://<cosmosdb_name>:<primary_master_key>@<cosmosdb_name>.documents.azure.cn:10250/mean?ssl=true&sslverifycertificate=false
App version:     0.5.0
MEAN.JS version: 0.5.0

在浏览器中导航到 http://localhost:8443Navigate to http://localhost:8443 in a browser. 在顶部菜单点击“注册” 并创建一个测试用户。Click Sign Up in the top menu and create a test user. 如果成功创建用户并登陆,那么应用会将数据写入 Azure 中的 Cosmos DB 数据库。If you are successful creating a user and signing in, then your app is writing data to the Cosmos DB database in Azure.

在终端中,通过键入 Ctrl+C 停止 Node.js。In the terminal, stop Node.js by typing Ctrl+C.

将应用部署到 AzureDeploy app to Azure

在此步骤中,要将 MongoDB 连接的 Node.js 应用程序部署到 Azure 应用服务。In this step, you deploy your MongoDB-connected Node.js application to Azure App Service.

配置部署用户Configure a deployment user

使用 az webapp deployment user set 命令配置部署凭据。Configure deployment credentials with the az webapp deployment user set command. 对 Web 应用进行 FTP 和本地 Git 部署时需要此部署用户。This deployment user is required for FTP and local Git deployment to a web app. 用户名和密码都为帐户级别。The user name and password are account level. 它们与 Azure 订阅凭据不同。They are different from your Azure subscription credentials.

在以下示例中,将 <username><password>(包括括号)替换为新的用户名和密码。In the following example, replace <username> and <password> (including brackets) with a new user name and password. 用户名在 Azure 中必须唯一。The user name must be unique within Azure. 密码长度必须至少为 8 个字符,其中包含以下 3 种元素中的两种:字母、数字、符号。The password must be at least eight characters long, with two of the following three elements: letters, numbers, symbols.

az webapp deployment user set --user-name <username> --password <password>

命令执行完成后你会获得一个 JSON 输出,密码显示为 nullYou should get a JSON output, with the password shown as null. 如果收到 'Conflict'. Details: 409 错误,请更改用户名。If you get a 'Conflict'. Details: 409 error, change the username. 如果收到 'Bad Request'. Details: 400 错误,请使用更强的密码。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

只需配置此部署用户一次;之后可对所有 Azure 部署使用此用户。You need to configure this deployment user only once; you can use it for all your Azure deployments.

Note

记录用户名和密码。Record the user name and password. 稍后需要使用它们来部署 Web 应用。You need them to deploy the web app later.

创建应用服务计划Create an App Service plan

使用 az appservice plan create 命令创建应用服务计划。Create an App Service plan with the az appservice plan create command.

应用服务计划指定托管应用的 Web 服务器场的位置、大小和功能。An App Service plan specifies the location, size, and features of the web server farm that hosts your app. 可以在托管多个应用时节省资金,方法是将多个 Web 应用配置为共用单个应用服务计划。You can save money when hosting multiple apps by configuring the web apps to share a single App Service plan.

应用服务计划定义:App Service plans define:

  • 区域(例如:中国东部、中国东部 2、中国北部、中国北部 2)Region (for example: China East, China East 2, China North, China North 2)
  • 实例大小(小、中、大)Instance size (small, medium, or large)
  • 规模计数(1 到 20 个实例)Scale count (1 to 20 instances)
  • SKU(免费、共享、基本、标准、高级)SKU (Free, Shared, Basic, Standard, or Premium)

以下示例在免费 定价层中创建名为 myAppServicePlan 的应用服务计划:The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE

创建应用服务计划后,Azure CLI 将显示类似于以下示例的信息:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "China North",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "China North",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

使用 az webapp create 命令在 myAppServicePlan 应用服务计划中创建一个 Web 应用。Create a web app in the myAppServicePlan App Service plan with the az webapp create command.

在 Azure CLI 中,可以使用 az webapp create 命令。在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。In the Azure CLI, you can use the az webapp create command.In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). 运行时设置为 NODE|6.9The runtime is set to NODE|6.9. 若要查看所有受支持的运行时,请运行 az webapp list-runtimesTo see all supported runtimes, run az webapp list-runtimes.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git

创建 Web 应用后,Azure CLI 会显示类似于以下示例的输出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

已创建了一个空的 Web 应用并启用了 Git 部署。You’ve created an empty web app, with git deployment enabled.

Note

Git 远程的 URL 将显示在 deploymentLocalGitUrl 属性中,其格式为 https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git. 保存此 URL,因为后面需要它。Save this URL as you need it later.

配置环境变量Configure an environment variable

默认情况下,MEAN.js 项目会在 Git 存储库外部保留 config/env/local-production.jsBy default, the MEAN.js project keeps config/env/local-production.js out of the Git repository. 因此对于 Azure 应用,请使用应用设置来定义 MongoDB 连接字符串。So for your Azure app, you use app settings to define your MongoDB connection string.

若要设置应用设置,请在 Azure CLI 中使用 az webapp config appsettings set 命令。To set app settings, use the az webapp config appsettings set command in Azure CLI.

以下示例在 Azure 应用中配置 MONGODB_URI 应用设置。The following example configures a MONGODB_URI app setting in your Azure app. 替换 <app_name> 、<cosmosdb_name> 和 <primary_master_key> 占位符。Replace the <app_name>, <cosmosdb_name>, and <primary_master_key> placeholders.

az webapp config appsettings set --name <app_name> --resource-group myResourceGroup --settings MONGODB_URI="mongodb://<cosmosdb_name>:<primary_master_key>@<cosmosdb_name>.documents.azure.cn:10250/mean?ssl=true"

在 Node.js 代码中,使用 process.env.MONGODB_URI 访问此应用设置,如同访问任何环境变量那样。In Node.js code, you access this app setting with process.env.MONGODB_URI, just like you would access any environment variable.

在本地 MEAN.js 存储库中,打开具有特定于生产环境的配置的 config/env/production.js(而不是 config/env/local-production.js)。In your local MEAN.js repository, open config/env/production.js (not config/env/local-production.js), which has production-environment specific configuration. 默认 MEAN.js 应用已配置为使用你所创建的 MONGODB_URI 环境变量。The default MEAN.js app is already configured to use the MONGODB_URI environment variable that you created.

db: {
  uri: ... || process.env.MONGODB_URI || ...,
  ...
},

从 Git 推送到 AzurePush to Azure from Git

回到本地终端窗口 ,将 Azure 远程功能添加到本地 Git 存储库。Back in the local terminal window, add an Azure remote to your local Git repository. <deploymentLocalGitUrl-from-create-step> 替换为在创建 Web 应用中保存的 Git 远程 URL。Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

使用以下命令推送到 Azure 远程功能以部署应用。Push to the Azure remote to deploy your app with the following command. 当 Git 凭据管理器提示输入凭据时,请确保输入在配置部署用户中创建的凭据,而不是用于登录到 Azure 门户的凭据。When prompted for credentials by Git Credential Manager, make sure that you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能需要花费几分钟时间运行。This command may take a few minutes to run. 运行时,该命令会显示类似于以下示例的信息:While running, it displays information similar to the following example:

Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 489 bytes | 0 bytes/s, done.
Total 5 (delta 3), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: Updating submodules.
remote: Preparing deployment for commit id '6c7c716eee'.
remote: Running custom deployment command...
remote: Running deployment command...
remote: Handling node.js deployment.
.
.
.
remote: Deployment successful.
To https://<app_name>.scm.chinacloudsites.cn/<app_name>.git
 * [new branch]      master -> master

可能已注意到,部署过程先运行 npm install,再运行 GulpYou may notice that the deployment process runs Gulp after npm install. 应用服务在部署期间不会运行 Gulp 或 Grunt 任务,因此该示例存储库的根目录中有两个额外文件用于启用它:App Service does not run Gulp or Grunt tasks during deployment, so this sample repository has two additional files in its root directory to enable it:

  • .deployment - 此文件告知应用服务将 bash deploy.sh 作为自定义部署脚本运行。.deployment - This file tells App Service to run bash deploy.sh as the custom deployment script.
  • deploy.sh - 自定义部署脚本。deploy.sh - The custom deployment script. 查看该文件可以发现,它先运行 npm installbower install,再运行 gulp prodIf you review the file, you will see that it runs gulp prod after npm install and bower install.

可以使用此方法将任何步骤添加到基于 Git 的部署。You can use this approach to add any step to your Git-based deployment. 如果重启 Azure 应用(无论何时),应用服务都不会重新运行这些自动化任务。If you restart your Azure app at any point, App Service doesn't rerun these automation tasks.

浏览到 Azure 应用Browse to the Azure app

使用 Web 浏览器浏览到已部署的应用。Browse to the deployed app using your web browser.

http://<app_name>.chinacloudsites.cn 

在顶部菜单中单击“注册” ,然后创建一个虚构的用户。Click Sign Up in the top menu and create a dummy user.

如果操作成功,且应用自动登录到已创建的用户,则 Azure 中的 MEAN.js 应用已连接至 MongoDB (Cosmos DB) 数据库。If you are successful and the app automatically signs in to the created user, then your MEAN.js app in Azure has connectivity to the MongoDB (Cosmos DB) database.

在 Azure 应用服务中运行的 MEAN.js 应用

选择“管理员”>“管理文章” ,添加一些文章。Select Admin > Manage Articles to add some articles.

祝贺你!Congratulations! 现已在 Azure 应用服务中运行数据驱动的 Node.js 应用。You're running a data-driven Node.js app in Azure App Service.

更新数据模型和重新部署Update data model and redeploy

在此步骤中,将更改 article 数据模型,并将其发布至 Azure。In this step, you change the article data model and publish your change to Azure.

更新数据模型Update the data model

打开 modules/articles/server/models/article.server.model.jsOpen modules/articles/server/models/article.server.model.js.

ArticleSchema 中,添加名为 commentString 类型。In ArticleSchema, add a String type called comment. 完成后,架构代码应该如下所示:When you're done, your schema code should look like this:

const ArticleSchema = new Schema({
  ...,
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  comment: {
    type: String,
    default: '',
    trim: true
  }
});

更新文章代码Update the articles code

更新剩余 articles 代码以使用 commentUpdate the rest of your articles code to use comment.

需修改的文件有五个,分别是服务器控制器以及四个客户端视图。There are five files you need to modify: the server controller and the four client views.

打开 modules/articles/server/controllers/articles.server.controller.jsOpen modules/articles/server/controllers/articles.server.controller.js.

update 函数中,为 article.comment 赋值。In the update function, add an assignment for article.comment. 下面的代码显示了完整的 update 功能:The following code shows the completed update function:

exports.update = function (req, res) {
  let article = req.article;

  article.title = req.body.title;
  article.content = req.body.content;
  article.comment = req.body.comment;

  ...
};

打开 modules/articles/client/views/view-article.client.view.htmlOpen modules/articles/client/views/view-article.client.view.html.

</section> 结尾标记正上方,添加下列行以显示 comment 和其余文章数据:Just above the closing </section> tag, add the following line to display comment along with the rest of the article data:

<p class="lead" ng-bind="vm.article.comment"></p>

打开 modules/articles/client/views/list-articles.client.view.htmlOpen modules/articles/client/views/list-articles.client.view.html.

</a> 结尾标记正上方,添加下列行以显示 comment 和其余文章数据:Just above the closing </a> tag, add the following line to display comment along with the rest of the article data:

<p class="list-group-item-text" ng-bind="article.comment"></p>

打开 modules/articles/client/views/admin/list-articles.client.view.htmlOpen modules/articles/client/views/admin/list-articles.client.view.html.

<div class="list-group"> 元素内,以及 </a> 结尾标记正上方,添加下列行以显示 comment 和其余文章数据:Inside the <div class="list-group"> element and just above the closing </a> tag, add the following line to display comment along with the rest of the article data:

<p class="list-group-item-text" data-ng-bind="article.comment"></p>

打开 modules/articles/client/views/admin/form-article.client.view.htmlOpen modules/articles/client/views/admin/form-article.client.view.html.

查找包含提交按钮的 <div class="form-group"> 元素,如下所示:Find the <div class="form-group"> element that contains the submit button, which looks like this:

<div class="form-group">
  <button type="submit" class="btn btn-default">{{vm.article._id ? 'Update' : 'Create'}}</button>
</div>

在此标记的正上方,添加另一个 <div class="form-group"> 元素,它允许人们编辑 comment 字段。Just above this tag, add another <div class="form-group"> element that lets people edit the comment field. 新元素应如下所示:Your new element should look like this:

<div class="form-group">
  <label class="control-label" for="comment">Comment</label>
  <textarea name="comment" data-ng-model="vm.article.comment" id="comment" class="form-control" cols="30" rows="10" placeholder="Comment"></textarea>
</div>

在本地测试更改Test your changes locally

保存所有更改。Save all your changes.

在本地终端窗口中,在生产模式下再次测试所做的更改。In the local terminal window, test your changes in production mode again.

# Bash
gulp prod
NODE_ENV=production node server.js

# Windows PowerShell
gulp prod
$env:NODE_ENV = "production" 
node server.js

在浏览器中导航至 http://localhost:8443,并确保已登录。Navigate to http://localhost:8443 in a browser and make sure that you're signed in.

选择“管理员”>“管理文章” ,然后选择“+” 按钮以添加文章。Select Admin > Manage Articles, then add an article by selecting the + button.

现在可看到新 Comment 文本框。You see the new Comment textbox now.

已向文章添加注释字段

在终端中,通过键入 Ctrl+C 停止 Node.js。In the terminal, stop Node.js by typing Ctrl+C.

发布对 Azure 所做的更改Publish changes to Azure

在本地终端窗口中,提交在 Git 中所做的更改,然后将代码更改推送到 Azure。In the local terminal window, commit your changes in Git, then push the code changes to Azure.

git commit -am "added article comment"
git push azure master

git push 完成后,请导航至 Azure 应用,并试用新功能。Once the git push is complete, navigate to your Azure app and try out the new functionality.

发布到 Azure 的模型和数据库更改

如果先前添加过任何文章,现在仍能看到它们。If you added any articles earlier, you still can see them. Cosmos DB 中的现有数据没有丢失。Existing data in your Cosmos DB is not lost. 同时,对数据架构的更新和现有数据都将保持不变。Also, your updates to the data schema and leaves your existing data intact.

流式传输诊断日志Stream diagnostic logs

当 Node.js 应用程序在 Azure 应用服务中运行时,可以将控制台日志通过管道传输到终端。While your Node.js application runs in Azure App Service, you can get the console logs piped to your terminal. 这样可以获得相同的诊断消息,以帮助调试应用程序错误。That way, you can get the same diagnostic messages to help you debug application errors.

若要启动日志流式处理,请使用 az webapp log tail 命令。To start log streaming, use the az webapp log tail command.

az webapp log tail --name <app_name> --resource-group myResourceGroup

启动日志流式处理后,请在浏览器中刷新 Azure 应用,以获取一些 Web 流量。Once log streaming has started, refresh your Azure app in the browser to get some web traffic. 现在将看到通过管道传送到终端的控制台日志。You now see console logs piped to your terminal.

通过键入 Ctrl+C,随时停止日志流式处理。Stop log streaming at any time by typing Ctrl+C.

管理 Azure 应用Manage your Azure app

转到 Azure 门户查看创建的应用。Go to the Azure portal to see the app you created.

在左侧菜单中单击“应用服务”,然后单击 Azure 应用的名称。 From the left menu, click App Services, then click the name of your Azure app.

在门户中导航到 Azure 应用

默认情况下,门户将显示应用的 “概述”页。By default, the portal shows your app's Overview page. 在此页中可以查看应用的运行状况。This page gives you a view of how your app is doing. 在此处还可以执行基本的管理任务,例如浏览、停止、启动、重新启动和删除。Here, you can also perform basic management tasks like browse, stop, start, restart, and delete. 页面左侧的选项卡显示可以打开的不同配置页。The tabs on the left side of the page show the different configuration pages you can open.

Azure 门户中的“应用服务”页

清理资源Clean up resources

若要清理资源,请运行以下命令:To clean up your resources, run the following command:

az group delete --name myResourceGroup

后续步骤Next steps

现已了解:What you learned:

  • 在 Azure 中创建 MongoDB 数据库Create a MongoDB database in Azure
  • 将 Node.js 应用连接到 MongoDBConnect a Node.js app to MongoDB
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 将日志从 Azure 流式传输到终端Stream logs from Azure to your terminal
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

转到下一教程,了解如何向应用映射自定义 DNS 名称。Advance to the next tutorial to learn how to map a custom DNS name to the app.