教學課程:在 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 ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.
  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

如果您選擇在本機安裝和使用 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 金鑰的話,此範例也會建立具有這些金鑰的 VM (名為 myVM )。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 殼層來安裝 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. 在我們的應用程式範例中,我們要新增書籍記錄到 MongoDB,這些記錄中包含了書籍名稱、isbn 編號、作者和頁數。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 殼層來設定 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 ] https://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. 我們也必須安裝本文剖析器套件,以協助我們處理透過要求傳遞至伺服器的 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 的資料夾,並於其中新增名為 server.js 的檔案,此檔案中包含 Web 伺服器的組態。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. 將網頁瀏覽器開啟到您為 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

在本教學課程中,您已建立 Web 應用程式以在 Linux VM 上使用 MEAN 堆疊來留下書籍記錄。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.