您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:在 Azure 中的 Linux 虚拟机上创建 MongoDB、Express、AngularJS 和 Node.js (MEAN) 堆栈Tutorial: Create a MongoDB, Express, AngularJS, and Node.js (MEAN) stack on a Linux virtual machine in Azure

本教程介绍如何在 Azure 中的 Linux 虚拟机 (VM) 上实现 MongoDB、Express、AngularJS 和 Node.js (MEAN) 堆栈。This tutorial shows you how to implement a MongoDB, Express, AngularJS, and Node.js (MEAN) stack on a Linux virtual machine (VM) in Azure. 通过创建的 MEAN 堆栈,可以在数据库中添加、删除和列出书籍。The MEAN stack that you create enables adding, deleting, and listing books in a database. 学习如何:You learn how to:

  • 创建 Linux VMCreate a Linux VM
  • 安装 Node.jsInstall Node.js
  • 安装 MongoDB 并设置服务器Install MongoDB and set up the server
  • 安装 Express 并设置服务器的路由Install Express and set up routes to the server
  • 使用 AngularJS 访问路由Access the routes with AngularJS
  • 运行应用程序Run the application

打开 Azure Cloud ShellOpen Azure Cloud Shell

Azure Cloud Shell 是免费的交互式 shell,可以使用它运行本文中的步骤。Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Cloud Shell 中预安装并配置了常用 Azure 工具供你与帐户一起使用。Common Azure tools are preinstalled and configured in Cloud Shell for you to use with your account. 只需选择“复制”按钮即可复制代码,将其粘贴到 Cloud Shell 中,然后按 Enter 来运行它。Just select the Copy button to copy the code, paste it in Cloud Shell, and then press Enter to run it. 可以通过多种方式打开 Cloud Shell,你可以选择其中任一种方式打开 Cloud Shell:There are a few ways to open Cloud Shell, you can choose any one of them to open Cloud Shell:

选择代码块右上角的“试用”。Select Try It in the upper-right corner of a code block. 本文中的 Cloud Shell
在浏览器中打开 Cloud Shell。Open Cloud Shell in your browser. https://shell.azure.com/bash
选择 Azure 门户右上角菜单上的“Cloud Shell”按钮。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. 门户中的 Cloud Shell

如果选择在本地安装并使用 CLI,本教程要求运行 Azure CLI 2.0.30 或更高版本。If you choose to install and use the CLI locally, this tutorial requires that you are running the Azure CLI version 2.0.30 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

创建 Linux VMCreate a Linux VM

使用 az group create 命令创建资源组,并使用 az vm create 命令创建 Linux VM。Create a resource group with the az group create command and create a Linux VM with the az vm create command. Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container into which Azure resources are deployed and managed.

以下示例使用 Azure CLI 在 eastus 位置创建名为 myResourceGroupMEAN 的资源组。The following example uses the Azure CLI to create a resource group named myResourceGroupMEAN in the eastus location. 将会创建一个包含 SSH 密钥(如果默认密钥位置不存在这些密钥)的、名为 myVM 的 VM。A VM is created named myVM with SSH keys if they do not already exist in a default key location. 若要使用一组特定的密钥,请使用 --ssh-key-value 选项。To use a specific set of keys, use the --ssh-key-value option.

az group create --name myResourceGroupMEAN --location eastus
az vm create \
    --resource-group myResourceGroupMEAN \
    --name myVM \
    --image UbuntuLTS \
    --admin-username azureuser \
    --admin-password 'Azure12345678!' \
    --generate-ssh-keys
az vm open-port --port 3300 --resource-group myResourceGroupMEAN --name myVM

创建 VM 后,Azure CLI 会显示类似于以下示例的信息:When the VM has been created, the Azure CLI shows information similar to the following example:

{
  "fqdns": "",
  "id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroupMEAN/providers/Microsoft.Compute/virtualMachines/myVM",
  "location": "eastus",
  "macAddress": "00-0D-3A-23-9A-49",
  "powerState": "VM running",
  "privateIpAddress": "10.0.0.4",
  "publicIpAddress": "13.72.77.9",
  "resourceGroup": "myResourceGroupMEAN"
}

记下 publicIpAddressTake note of the publicIpAddress. 此地址用于访问 VM。This address is used to access the VM.

使用以下命令来与 VM 建立 SSH 会话。Use the following command to create an SSH session with the VM. 请确保使用正确的公共 IP 地址。Make sure to use the correct public IP address. 在上例中,我们的 IP 地址为 13.72.77.9。In our example above our IP address was 13.72.77.9.

ssh azureuser@13.72.77.9

安装 Node.jsInstall Node.js

Node.js 是构建在 Chrome V8 JavaScript 引擎基础之上的 JavaScript 运行时。Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. 本教程使用 Node.js 来设置 Express 路由和 AngularJS 控制器。Node.js is used in this tutorial to set up the Express routes and AngularJS controllers.

在 VM 上,使用通过 SSH 打开的 bash shell 安装 Node.js。On the VM, using the bash shell that you opened with SSH, install Node.js.

sudo apt-get install -y nodejs

安装 MongoDB 并设置服务器Install MongoDB and set up the server

MongoDB 将数据存储在灵活的、类似于 JSON 的文档中。MongoDB stores data in flexible, JSON-like documents. 数据库中的字段根据文档的不同而异,数据结构随时可发生变化。Fields in a database can vary from document to document and data structure can be changed over time. 针对示例应用程序,我们要将包含书名、ISBN 编号、作者和页数的书籍记录添加到 MongoDB。For our example application, we are adding book records to MongoDB that contain book name, isbn number, author, and number of pages.

  1. 在 VM 上,使用通过 SSH 打开的 bash shell 设置 MongoDB 密钥。On the VM, using the bash shell that you opened with SSH, set the MongoDB key.

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
    echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
    
  2. 使用密钥更新包管理器。Update the package manager with the key.

    sudo apt-get update
    
  3. 安装 MongoDB。Install MongoDB.

    sudo apt-get install -y mongodb
    
  4. 启动服务器。Start the server.

    sudo service mongodb start
    
  5. 还需要安装 body-parser 包,以帮助我们处理在请求中传递给服务器的 JSON。We also need to install the body-parser package to help us process the JSON passed in requests to the server.

    安装 npm 包管理器。Install the npm package manager.

    sudo apt-get install npm
    

    安装正文分析器包。Install the body parser package.

    sudo npm install body-parser
    
  6. 创建名为 Books 的文件夹,并将包含 Web 服务器配置的、名为 server.js 的文件添加到该文件夹。Create a folder named Books and add a file to it named server.js that contains the configuration for the web server.

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(express.static(__dirname + '/public'));
    app.use(bodyParser.json());
    require('./apps/routes')(app);
    app.set('port', 3300);
    app.listen(app.get('port'), function() {
        console.log('Server up: http://localhost:' + app.get('port'));
    });
    

安装 Express 并设置服务器的路由Install Express and set up routes to the server

Express 是一个微型的灵活 Node.js Web 应用程序框架,为 Web 和移动应用程序提供功能。Express is a minimal and flexible Node.js web application framework that provides features for web and mobile applications. 本教程使用 Express 将书籍信息传入和传出 MongoDB 数据库。Express is used in this tutorial to pass book information to and from our MongoDB database. Mongoose 提供简洁的基于架构的解决方案来为应用程序数据建模。Mongoose provides a straight-forward, schema-based solution to model your application data. 本教程使用 Mongoose 来为数据库提供书籍架构。Mongoose is used in this tutorial to provide a book schema for the database.

  1. 安装 Express 和 Mongoose。Install Express and Mongoose.

    sudo npm install express mongoose
    
  2. Books 文件夹中,创建名为 apps 的文件夹,并添加包含所定义的 Express 路由的、名为 routes.js 的文件。In the Books folder, create a folder named apps and add a file named routes.js with the express routes defined.

    var Book = require('./models/book');
    module.exports = function(app) {
      app.get('/book', function(req, res) {
        Book.find({}, function(err, result) {
          if ( err ) throw err;
          res.json(result);
        });
      }); 
      app.post('/book', function(req, res) {
        var book = new Book( {
          name:req.body.name,
          isbn:req.body.isbn,
          author:req.body.author,
          pages:req.body.pages
        });
        book.save(function(err, result) {
          if ( err ) throw err;
          res.json( {
            message:"Successfully added book",
            book:result
          });
        });
      });
      app.delete("/book/:isbn", function(req, res) {
        Book.findOneAndRemove(req.query, function(err, result) {
          if ( err ) throw err;
          res.json( {
            message: "Successfully deleted the book",
            book: result
          });
        });
      });
      var path = require('path');
      app.get('*', function(req, res) {
        res.sendfile(path.join(__dirname + '/public', 'index.html'));
      });
    };
    
  3. apps 文件夹中,创建名为 models 的文件夹,并添加包含所定义的书籍模型配置的、名为 book.js 的文件。In the apps folder, create a folder named models and add a file named book.js with the book model configuration defined.

    var mongoose = require('mongoose');
    var dbHost = 'mongodb://localhost:27017/test';
    mongoose.connect(dbHost);
    mongoose.connection;
    mongoose.set('debug', true);
    var bookSchema = mongoose.Schema( {
      name: String,
      isbn: {type: String, index: true},
      author: String,
      pages: Number
    });
    var Book = mongoose.model('Book', bookSchema);
    module.exports = mongoose.model('Book', bookSchema); 
    

使用 AngularJS 访问路由Access the routes with AngularJS

AngularJS 提供一个 Web 框架用于在 Web 应用程序中创建动态视图。AngularJS provides a web framework for creating dynamic views in your web applications. 本教程使用 AngularJS 将网页与 Express 相连接,并针对书籍数据库执行操作。In this tutorial, we use AngularJS to connect our web page with Express and perform actions on our book database.

  1. 将目录切换回到 Books (cd ../..),然后创建名为 public 的文件夹,并添加包含所定义的控制器配置的、名为 script.js 的文件。Change the directory back up to Books (cd ../..), and then create a folder named public and add a file named script.js with the controller configuration defined.

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
      $http( {
        method: 'GET',
        url: '/book'
      }).then(function successCallback(response) {
        $scope.books = response.data;
      }, function errorCallback(response) {
        console.log('Error: ' + response);
      });
      $scope.del_book = function(book) {
        $http( {
          method: 'DELETE',
          url: '/book/:isbn',
          params: {'isbn': book.isbn}
        }).then(function successCallback(response) {
          console.log(response);
        }, function errorCallback(response) {
          console.log('Error: ' + response);
        });
      };
      $scope.add_book = function() {
        var body = '{ "name": "' + $scope.Name + 
        '", "isbn": "' + $scope.Isbn +
        '", "author": "' + $scope.Author + 
        '", "pages": "' + $scope.Pages + '" }';
        $http({
          method: 'POST',
          url: '/book',
          data: body
        }).then(function successCallback(response) {
          console.log(response);
        }, function errorCallback(response) {
          console.log('Error: ' + response);
        });
      };
    });
    
  2. public 文件夹中,创建包含所定义的网页的、名为 index.html 的文件。In the public folder, create a file named index.html with the web page defined.

    <!doctype html>
    <html ng-app="myApp" ng-controller="myCtrl">
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="script.js"></script>
      </head>
      <body>
        <div>
          <table>
            <tr>
              <td>Name:</td> 
              <td><input type="text" ng-model="Name"></td>
            </tr>
            <tr>
              <td>Isbn:</td>
              <td><input type="text" ng-model="Isbn"></td>
            </tr>
            <tr>
              <td>Author:</td> 
              <td><input type="text" ng-model="Author"></td>
            </tr>
            <tr>
              <td>Pages:</td>
              <td><input type="number" ng-model="Pages"></td>
            </tr>
          </table>
          <button ng-click="add_book()">Add</button>
        </div>
        <hr>
        <div>
          <table>
            <tr>
              <th>Name</th>
              <th>Isbn</th>
              <th>Author</th>
              <th>Pages</th>
            </tr>
            <tr ng-repeat="book in books">
              <td><input type="button" value="Delete" data-ng-click="del_book(book)"></td>
              <td>{{book.name}}</td>
              <td>{{book.isbn}}</td>
              <td>{{book.author}}</td>
              <td>{{book.pages}}</td>
            </tr>
          </table>
        </div>
      </body>
    </html>
    

运行应用程序Run the application

  1. 将目录切换回到 Books (cd ..),并通过运行以下命令启动服务器:Change the directory back up to Books (cd ..) and start the server by running this command:

    nodejs server.js
    
  2. 打开 Web 浏览器并导航到针对 VM 记录的地址。Open a web browser to the address that you recorded for the VM. 例如,http://13.72.77.9:3300For example, http://13.72.77.9:3300. 应显示以下页面所示的内容:You should see something like the following page:

    书籍记录

  3. 在文本框中输入数据并单击“添加”。Enter data into the textboxes and click Add. 例如:For example:

    添加书籍记录

  4. 刷新页面后,应会看到以下页面所示的内容:After refreshing the page, you should see something like this page:

    列出书籍记录

  5. 可以单击“删除”并从数据库中删除书籍记录。You could click Delete and remove the book record from the database.

后续步骤Next steps

本教程已创建一个可在 Linux VM 上使用 MEAN 堆栈跟踪书籍记录的 Web 应用程序。In this tutorial, you created a web application that keeps track of book records using a MEAN stack on a Linux VM. 你已了解如何:You learned how to:

  • 创建 Linux VMCreate a Linux VM
  • 安装 Node.jsInstall Node.js
  • 安装 MongoDB 并设置服务器Install MongoDB and set up the server
  • 安装 Express 并设置服务器的路由Install Express and set up routes to the server
  • 使用 AngularJS 访问路由Access the routes with AngularJS
  • 运行应用程序Run the application

转到下一教程,了解如何使用 SSL 证书保护 Web 服务器。Advance to the next tutorial to learn how to secure web servers with SSL certificates.