使用 Azure Cosmos DB 的用于 MongoDB 的 API 创建 Angular 应用 - 创建 Node.js Express 应用Create an Angular app with Azure Cosmos DB's API for MongoDB - Create a Node.js Express app

本教程包含多个部分,演示了如何通过 Express 和 Angular 创建以 Node.js 编写的新应用,然后将其连接到使用 Cosmos DB 的用于 MongoDB 的 API 配置的 Cosmos 帐户This multi-part tutorial demonstrates how to create a new app written in Node.js with Express and Angular and then connect it to your Cosmos account configured with Cosmos DB's API for MongoDB.

本教程的第 2 部分基于简介,涵盖以下任务:Part 2 of the tutorial builds on the introduction and covers the following tasks:

  • 安装 Angular CLI 和 TypeScriptInstall the Angular CLI and TypeScript
  • 使用 Angular 创建新项目Create a new project using Angular
  • 使用 Express 框架生成应用Build out the app using the Express framework
  • 在 Postman 中测试应用Test the app in Postman

先决条件Prerequisites

在开始教程的此部分之前,请确保已观看简介视频Before starting this part of the tutorial, ensure you've watched the introduction video.

本教程还需要:This tutorial also requires:

提示

本教程介绍生成应用程序的各个步骤。This tutorial walks you through the steps to build the application step-by-step. 若要下载完成的项目,可从 GitHub 上的 angular-cosmosdb 存储库获取完成的应用程序。If you want to download the finished project, you can get the completed application from the angular-cosmosdb repo on GitHub.

安装 Angular CLI 和 TypeScriptInstall the Angular CLI and TypeScript

  1. 打开 Windows 命令提示符或 Mac Terminal 窗口并安装 Angular CLI。Open a Windows Command Prompt or Mac Terminal window and install the Angular CLI.

    npm install -g @angular/cli
    
  2. 在提示符处输入以下命令,安装 TypeScript。Install TypeScript by entering the following command in the prompt.

    npm install -g typescript
    

使用 Angular CLI 创建新项目Use the Angular CLI to create a new project

  1. 在命令提示符处转到需在其中创建新项目的文件夹,然后运行以下命令。At the command prompt, change to the folder where you want to create your new project, then run the following command. 此命令创建名为 angular-cosmosdb 的新文件夹和项目,并安装新应用所需的 Angular 组件。This command creates a new folder and project named angular-cosmosdb and installs the Angular components required for a new app. 它会使用最低设置 (--minimal),并指定该项目使用 Sass(一种带 --style scss 标志的类似 CSS 的语法)。It uses the minimal setup (--minimal), and specifies that the project uses Sass (a CSS-like syntax with the flag --style scss).

    ng new angular-cosmosdb --minimal --style scss
    
  2. 完成该命令后,将目录转到 src/client 文件夹。Once the command completes, change directories into the src/client folder.

    cd angular-cosmosdb
    
  3. 然后在 Visual Studio Code 中打开该文件夹。Then open the folder in Visual Studio Code.

    code .
    

使用 Express 框架生成应用Build the app using the Express framework

  1. 在 Visual Studio Code 的“资源管理器”窗格中,右键单击 src 文件夹,单击“新建文件夹”,然后将新文件夹命名为“server”。In Visual Studio Code, in the Explorer pane, right-click the src folder, click New Folder, and name the new folder server.

  2. 在“资源管理器”窗格中,右键单击“server”文件夹,单击“新建文件”,然后将新文件命名为“index.js”。In the Explorer pane, right-click the server folder, click New File, and name the new file index.js.

  3. 回到命令提示符处,使用以下命令安装正文分析器。Back at the command prompt, use the following command to install the body parser. 这有助于应用分析通过 API 传入的 JSON 数据。This helps our app parse the JSON data that are passed in through the APIs.

    npm i express body-parser --save
    
  4. 将以下代码复制到 Visual Studio Code 的 index.js 文件中。In Visual Studio Code, copy the following code into the index.js file. 此代码:This code:

    • 引用 ExpressReferences Express
    • 拉入 body-parser,用于读取请求正文中的 JSON 数据Pulls in the body-parser for reading JSON data in the body of requests
    • 使用称为 path 的内置功能Uses a built-in feature called path
    • 设置根变量,方便查找代码所处位置Sets root variables to make it easier to find where our code is located
    • 设置端口Sets up a port
    • 启动 ExpressCranks up Express
    • 告知应用如何使用可以为服务器提供服务的中间件Tells the app how to use the middleware that were going to be using to serve up the server
    • 提供 dist 文件夹中将会成为静态内容的所有内容Serves everything that's in the dist folder, which will be the static content
    • 为应用程序提供服务,为服务器上找不到的任何 GET 请求提供 index.html(用于深层链接)Serves up the application, and serves index.html for any GET requests not found on the server (for deep links)
    • 通过 app.listen 启动服务器Starts the server with app.listen
    • 使用 arrow 函数来记录端口处于活动状态这一情况Uses an arrow function to log that the port is alive
    const express = require('express');
    const bodyParser = require('body-parser');
    const path = require('path');
    const routes = require('./routes');
    
    const root = './';
    const port = process.env.PORT || '3000';
    const app = express();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(express.static(path.join(root, 'dist/angular-cosmosdb')));
    app.use('/api', routes);
    app.get('*', (req, res) => {
     res.sendFile('dist/angular-cosmosdb/index.html', {root});
    });
    
    app.listen(port, () => console.log(`API running on localhost:${port}`));
    
  5. 在 Visual Studio Code 的“资源管理器”窗格中,右键单击 server 文件夹,然后单击“新建文件”。In Visual Studio Code, in the Explorer pane, right-click the server folder, and then click New file. 将新文件命名为 routes.js。Name the new file routes.js.

  6. 将以下代码复制到 routes.js 中。Copy the following code into routes.js. 此代码:This code:

    • 引用 Express 路由器References the Express router

    • 获取 heroGets the heroes

    • 发送回适用于已定义 hero 的 JSONSends back the JSON for a defined hero

      const express = require('express');
      const router = express.Router();
      
      router.get('/heroes', (req, res) => {
      res.send(200, [
      {"id": 10, "name": "Starlord", "saying": "oh yeah"}
      ])
      });
      
      module.exports=router;
      
  7. 保存所有修改过的文件。Save all your modified files.

  8. 在 Visual Studio Code 中,单击“调试”按钮 ,单击“齿轮”按钮 此时会在 Visual Studio Code 中打开新的 launch.json 文件。The new launch.json file opens in Visual Studio Code.

  9. 在 launch.json 文件的第 11 行将 "${workspaceFolder}\\server" 更改为 "program": "${workspaceRoot}/src/server/index.js",然后保存文件。On line 11 of the launch.json file, change "${workspaceFolder}\\server" to "program": "${workspaceRoot}/src/server/index.js" and save the file.

  10. 单击“启动调试”按钮 运行该应用。

    应用应该正常运行。The app should run without errors.

使用 Postman 来测试应用Use Postman to test the app

  1. 现在请打开 Postman,将 http://localhost:3000/api/heroes 置于 GET 框中。Now open Postman and put http://localhost:3000/api/heroes in the GET box.

  2. 单击“发送”按钮,从应用获取 JSON 响应。Click the Send button and get the json response from the app.

    该响应显示应用在本地启动并运行。This response shows the app is up and running locally.

    显示请求和响应的 Postman

后续步骤Next steps

在本教程的此部分,你已完成以下操作:In this part of the tutorial, you've done the following:

  • 使用 Angular CLI 创建 Node.js 项目Created a Node.js project using the Angular CLI
  • 使用 Postman 测试应用Tested the app using Postman

你可以转到本教程的下一部分来生成 UI。You can proceed to the next part of the tutorial to build the UI.