如何使用移动应用 Node.js SDKHow to use the Mobile Apps Node.js SDK

本文提供详细的信息和示例,说明如何在 Azure 应用服务的移动应用功能中使用 Node.js 后端。This article provides detailed information and examples that show how to work with a Node.js back end in the Mobile Apps feature of Azure App Service.

介绍Introduction

使用移动应用可将移动优化的数据访问 Web API 添加到 Web 应用程序。Mobile Apps provides the capability to add a mobile-optimized data access Web API to a web application. 提供的移动应用 SDK 适用于 ASP.NET 和 Node.js Web 应用程序。The Mobile Apps SDK is provided for ASP.NET and Node.js web applications. 此 SDK 提供以下操作:The SDK provides the following operations:

  • 数据访问的表操作(读取、插入、更新、删除)Table operations (read, insert, update, delete) for data access
  • 自定义 API 操作Custom API operations

这两种操作都可用于 Azure 应用服务允许的所有标识提供者之间的身份验证。Both operations provide for authentication across all identity providers that Azure App Service allows. 这些提供者包括 Microsoft 等社交标识提供者,以及用于企业标识的 Azure Active Directory。These providers include social identity providers such as Microsoft and Azure Active Directory for enterprise identity.

可以 在 GitHub 上的示例目录中找到每种用例的示例。You can find samples for each use case in the samples directory on GitHub.

支持的平台Supported platforms

移动应用 Node.js SDK 支持 Node 的当前 LTS 版本及更高版本。The Mobile Apps Node.js SDK supports the current LTS release of Node and later. 目前,最新 LTS 版本为 Node v4.5.0。Currently, the latest LTS version is Node v4.5.0. 其他 Node 版本可能有效,但不受支持。Other versions of Node might work but are not supported.

Azure 移动应用 Node.js SDK 支持两个数据库驱动程序:The Mobile Apps Node.js SDK supports two database drivers:

  • node-mssqll 驱动程序支持 Azure SQL 数据库和本地 SQL Server 实例。The node-mssql driver supports Azure SQL Database and local SQL Server instances.
  • sqlite3 驱动程序仅支持单个实例上的 SQLite 数据库。The sqlite3 driver supports SQLite databases on a single instance only.

使用命令行创建基本 Node.js 后端Create a basic Node.js back end by using the command line

每个移动应用 Node.js 后端都以 ExpressJS 应用程序的形式启动。Every Mobile Apps Node.js back end starts as an ExpressJS application. 在适用于 Node.js 的 Web 服务框架中,ExpressJS 最广为使用。ExpressJS is the most popular web service framework available for Node.js. 可按以下方式创建基本的 Express 应用程序:You can create a basic Express application as follows:

  1. 在命令窗口或 PowerShell 窗口中,为项目创建目录:In a command or PowerShell window, create a directory for your project:

    mkdir basicapp
    
  2. 运行 npm init 初始化包结构:Run npm init to initialize the package structure:

    cd basicapp
    npm init
    

    npm init 命令将提出一系列问题以初始化项目。The npm init command asks a set of questions to initialize the project. 查看示例输出:See the example output:

    npm init 输出

  3. 从 npm 存储库安装 expressazure-mobile-apps 库:Install the express and azure-mobile-apps libraries from the npm repository:

    npm install --save express azure-mobile-apps
    
  4. 创建 app.js 文件,实现基本移动服务器:Create an app.js file to implement the basic mobile server:

    var express = require('express'),
        azureMobileApps = require('azure-mobile-apps');
    
    var app = express(),
        mobile = azureMobileApps();
    
    // Define a TodoItem table.
    mobile.tables.add('TodoItem');
    
    // Add the Mobile API so it is accessible as a Web API.
    app.use(mobile);
    
    // Start listening on HTTP.
    app.listen(process.env.PORT || 3000);
    

此应用程序创建具有单个终结点 (/tables/TodoItem) 的移动优化 Web API,让用户使用动态架构访问基础 SQL 数据存储,而无需经过身份验证。This application creates a mobile-optimized Web API with a single endpoint (/tables/TodoItem) that provides unauthenticated access to an underlying SQL data store by using a dynamic schema. 它适用于以下客户端库快速入门:It is suitable for following the client library quickstarts:

可以在 GitHub 上的 basicapp 示例中找到此基本应用程序的代码。You can find the code for this basic application in the basicapp sample on GitHub.

使用 Visual Studio 2015 创建 Node.js 后端Create a Node.js back end by using Visual Studio 2015

Visual Studio 2015 需要使用一个扩展在 IDE 中开发 Node.js 应用程序。Visual Studio 2015 requires an extension to develop Node.js applications within the IDE. 首先,请安装 Node.js Tools 1.1 for Visual StudioTo start, install the Node.js Tools 1.1 for Visual Studio. 完成安装后,创建 Express 4.x 应用程序:When you finish the installation, create an Express 4.x application:

  1. 打开“新建项目” 对话框(从“文件” > “新建” > “项目” )。Open the New Project dialog box (from File > New > Project).

  2. 展开“模板” > “JavaScript” > “Node.js” 。Expand Templates > JavaScript > Node.js.

  3. 选择“基本 Azure Node.js Express 4 应用程序” 。Select Basic Azure Node.js Express 4 Application.

  4. 填写项目名称。Fill in the project name. 选择“确定” 。Select OK.

    Visual Studio 2015 中的“新建项目”

  5. 右键单击“npm” 节点,选择“安装新的 npm 包” 。Right-click the npm node and select Install New npm packages.

  6. 创建第一个 Node.js 应用程序时,可能需要刷新 npm 目录。You might need to refresh the npm catalog after you create your first Node.js application. 根据需要选择“刷新” 。Select Refresh if necessary.

  7. 在搜索框中输入 azure-mobile-appsEnter azure-mobile-apps in the search box. 选择 azure-mobile-apps 2.0.0 包,然后选择“安装包” 。Select the azure-mobile-apps 2.0.0 package, and then select Install Package.

    安装新的 npm 包

  8. 选择“关闭” 。Select Close.

  9. 打开 app.js 文件,添加对移动应用 SDK 的支持。Open the app.js file to add support for the Mobile Apps SDK. 在库 require 语句底部的第 6 行,添加以下代码:At line 6 at the bottom of the library require statements, add the following code:

    var bodyParser = require('body-parser');
    var azureMobileApps = require('azure-mobile-apps');
    

    在其他 app.use 语句之后大约第 27 行,添加以下代码:At approximately line 27 after the other app.use statements, add the following code:

    app.use('/users', users);
    
    // Mobile Apps initialization
    var mobile = azureMobileApps();
    mobile.tables.add('TodoItem');
    app.use(mobile);
    

    保存文件。Save the file.

  10. 在本地运行应用程序(API 会在 http://localhost:3000 上提供),或发布到 Azure。Either run the application locally (the API is served on http://localhost:3000) or publish to Azure.

使用 Azure 门户创建 Node.js 后端Create a Node.js back end by using the Azure portal

可以在 Azure 门户中直接创建移动应用后端。You can create a Mobile Apps back end right in the Azure portal. 可以完成以下步骤,或根据创建移动应用教程同时创建客户端和服务器。You can either complete the following steps or create a client and server together by following the Create a mobile app tutorial. 本教程包含以下说明的简化版本,最适合用于概念认证项目。The tutorial contains a simplified version of these instructions and is best for proof-of-concept projects.

  1. 登录到 Azure 门户Sign in at the Azure portal.

  2. 单击“+新建” > “Web + 移动” > “移动应用”,并为移动应用后端提供一个名称。 Select +NEW > Web + Mobile > Mobile App, and then provide a name for your Mobile Apps back end.

  3. 在“资源组”下 ,选择一个现有资源组,或创建一个新资源组(使用与应用相同的名称)。For Resource Group, select an existing resource group, or create a new one (by using the same name as your app).

  4. 对于“应用服务计划” ,请选择默认计划(在标准层中)。For App Service plan, the default plan (in the Standard tier) is selected. 还可以选择其他计划,或创建一个新计划You can also select a different plan, or create a new one.

    应用服务计划的设置将确定与应用关联的位置、功能、成本和计算资源The App Service plan's settings determine the location, features, cost, and compute resources associated with your app. 有关应用服务计划以及如何在不同定价层和所需位置中创建新计划的详细信息,请参阅 Azure 应用服务计划深入概述For more about App Service plans and how to create a new plan in a different pricing tier and in your desired location, see Azure App Service plans in-depth overview.

  5. 选择“创建” 。Select Create. 此步骤创建移动应用后端。This step creates the Mobile Apps back end.

  6. 在新的移动应用后端的“设置”窗格中,依次选择“快速启动”>客户端应用平台 >“连接数据库”。 In the Settings pane for the new Mobile Apps back end, select Quick start > your client app platform > Connect a database.

    用于连接数据库的选项选择

  7. 在“添加数据连接” 窗格中,选择“SQL 数据库” > “创建新数据库”。 In the Add data connection pane, select SQL Database > Create a new database. 输入数据库名称,选择一个定价层,然后选择“服务器” 。Enter the database name, choose a pricing tier, and then select Server. 可以重复使用此新数据库。You can reuse this new database. 如果在同一位置已有数据库,则可选择“使用现有数据库” 。If you already have a database in the same location, you can instead choose Use an existing database. 不建议使用位于不同位置的数据库,因为有带宽成本且延迟较高。We don't recommend the use of a database in a different location, due to bandwidth costs and higher latency.

    选择数据库

  8. 在“新服务器”窗格中,在“服务器名称”框中输入唯一服务器名称,提供登录名和密码,选中“允许 Azure 服务访问服务器”,并选择“确定”。 In the New server pane, enter a unique server name in the Server name box, provide a login and password, select Allow Azure services to access server, and select OK. 此步骤创建新数据库。This step creates the new database.

  9. 回到“添加数据连接”窗格中,选择“连接字符串”,输入数据库的登录名和密码值,并选择“确定”。 Back in the Add data connection pane, select Connection string, enter the login and password values for your database, and select OK.

    等待几分钟,等数据库署成功后再继续操作。Wait a few minutes for the database to be deployed successfully before you proceed.

返回“开始使用” 窗格,在“创建表 API” 下面,选择“Node.js” 作为后端语言。Back in the Get started pane, under Create a table API, choose Node.js as your back-end language. 选中“我已了解此操作会覆盖所有站点内容” 框,并选择“创建 TodoItem 表” 。Select the box for I acknowledge that this will overwrite all site contents, and then select Create TodoItem table.

使用 Git 下载 Node.js 后端快速入门代码项目Download the Node.js back-end quickstart code project by using Git

使用门户的“快速启动” 窗格创建 Node.js 移动应用后端时,系统将创建 Node.js 项目并将其部署到站点。When you create a Node.js Mobile Apps back end by using the portal's Quick start pane, a Node.js project is created for you and deployed to your site. 可以在门户中添加表和 API,以及编辑 Node.js 后端的代码文件。In the portal, you can add tables and APIs, and edit code files for the Node.js back end. 还可以使用多种部署工具下载后端项目,以便添加或修改表和 API,并重新发布项目。You can also use various deployment tools to download the back-end project so that you can add or modify tables and APIs, and then republish the project. 有关详细信息,请参阅 Azure 应用服务部署指南For more information, see the Azure App Service deployment guide.

以下过程使用 Git 存储库下载快速入门项目代码:The following procedure uses a Git repository to download the quickstart project code:

  1. 安装 Git(如果尚未安装)。Install Git, if you haven't already done so. 安装 Git 所需的步骤因操作系统的不同而异。The steps required to install Git vary between operating systems. 有关操作系统特定的分发和安装指南,请参阅安装 GitFor operating system-specific distributions and installation guidance, see Installing Git.

  2. 若要启用后端站点的 GIT 存储库,请参阅准备存储库See Prepare your repository to enable the Git repository for your back-end site. 记下部署用户名和密码。Make a note of the deployment username and password.

  3. 在移动应用后端的窗格中,记下“Git 克隆 URL” 设置。In the pane for your Mobile Apps back end, make a note of the Git clone URL setting.

  4. 使用 Git 克隆 URL 执行 git clone 命令。Execute the git clone command by using the Git clone URL. 根据需要输入密码,如以下示例所示:Enter your password when required, as in the following example:

    $ git clone https://username@todolist.scm.chinacloudsites.cn:443/todolist.git
    
  5. 浏览到本地目录(在上述示例中为 /todolist),可以看到项目文件已下载。Browse to the local directory (/todolist in the preceding example), and notice that project files have been downloaded. /tables 目录中找到 todoitem.json 文件。Locate the todoitem.json file in the /tables directory. 此文件定义表上的权限。This file defines permissions on the table. 另外,在同一目录中找到 todoitem.js 文件。Also find the todoitem.js file in the same directory. 该文件定义表的 CRUD 操作脚本。It defines the CRUD operation scripts for the table.

  6. 更改项目文件之后,请运行以下命令添加、提交更改,然后将更改上传到站点:After you make changes to project files, run the following commands to add, commit, and then upload the changes to the site:

    $ git commit -m "updated the table script"
    $ git push origin master
    

    将新文件添加到项目时,必须先运行 git add . 命令。When you add new files to the project, you first need to run the git add . command.

每次将一组新的提交内容推送到站点时,将重新发布站点。The site is republished every time a new set of commits is pushed to the site.

将 Node.js 后端发布到 AzurePublish your Node.js back end to Azure

Azure 提供了许多将移动应用 Node.js 后端发布到 Azure 服务的机制。Azure provides many mechanisms for publishing your Mobile Apps Node.js back end to the Azure service. 这些机制包括已集成到 Visual Studio 的部署工具、命令行工具,以及基于源代码管理的持续部署选项。These mechanisms include deployment tools integrated into Visual Studio, command-line tools, and continuous deployment options based on source control. 有关详细信息,请参阅 Azure 应用服务部署指南For more information, see the Azure App Service deployment guide.

Azure 应用服务提供有关 Node.js 应用程序的具体建议,请在发布后端之前查看:Azure App Service has specific advice for Node.js applications that you should review before you publish the back end:

启用应用程序的主页Enable a home page for your application

许多应用程序是 Web 和移动应用的组合。Many applications are a combination of web and mobile apps. 可以使用 ExpressJS 框架组合两个分面。You can use the ExpressJS framework to combine the two facets. 但有时,我们可能只想要实现移动接口。Sometimes, however, you might want to only implement a mobile interface. 移动接口用于提供主页,确保应用服务已启动并在运行。It's useful to provide a home page to ensure that the app service is up and running. 可以提供自己的主页,或启用临时主页。You can either provide your own home page or enable a temporary home page. 若要启用临时主页,请使用以下代码来实例化移动应用:To enable a temporary home page, use the following code to instantiate Mobile Apps:

var mobile = azureMobileApps({ homePage: true });

如果想要让此选项仅在本地开发时可供使用,可以将此设置添加到 azureMobile.js 文件。If you only want this option available when developing locally, you can add this setting to your azureMobile.js file.

表操作Table operations

azure-mobile-apps Node.js Server SDK 提供将存储在 Azure SQL 数据库中的表公开为 Web API 的机制。The azure-mobile-apps Node.js Server SDK provides mechanisms to expose data tables stored in Azure SQL Database as a Web API. 它提供五个操作:It provides five operations:

操作Operation 说明Description
GET /tables/tablenameGET /tables/tablename 获取表中的所有记录。Get all records in the table.
GET /tables/tablename/:idGET /tables/tablename/:id 获取表中的特定记录。Get a specific record in the table.
POST /tables/tablenamePOST /tables/tablename 在表中创建记录。Create a record in the table.
PATCH /tables/tablename/:idPATCH /tables/tablename/:id 在表中更新记录。Update a record in the table.
DELETE /tables/tablename/:idDELETE /tables/tablename/:id 删除表中的记录。Delete a record in the table.

此 Web API 支持 OData,并扩展表架构以支持脱机数据同步This Web API supports OData and extends the table schema to support offline data sync.

使用动态架构定义表Define tables by using a dynamic schema

表必须先经过定义才能使用。Before you can use a table, you must define it. 可以使用静态架构来定义表(在架构中定义列),或者动态定义表(SDK 根据传入的请求控制架构)。You can define tables by using a static schema (where you define the columns in the schema) or dynamically (where the SDK controls the schema based on incoming requests). 此外,可以通过将 JavaScript 代码添加到定义,来控制 Web API 的特定层面。In addition, you can control specific aspects of the Web API by adding JavaScript code to the definition.

根据最佳做法,应在 tables 目录中的 JavaScript 文件内定义每个表,并使用 tables.import() 方法导入表。As a best practice, you should define each table in a JavaScript file in the tables directory, and then use the tables.import() method to import the tables. 扩展 basic-app 示例后,调整 app.js 文件:Extending the basic-app sample, you would adjust the app.js file:

var express = require('express'),
    azureMobileApps = require('azure-mobile-apps');

var app = express(),
    mobile = azureMobileApps();

// Define the database schema that is exposed.
mobile.tables.import('./tables');

// Provide initialization of any tables that are statically defined.
mobile.tables.initialize().then(function () {
    // Add the Mobile API so it is accessible as a Web API.
    app.use(mobile);

    // Start listening on HTTP.
    app.listen(process.env.PORT || 3000);
});

在 ./tables/TodoItem.js 中定义表:Define the table in ./tables/TodoItem.js:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Additional configuration for the table goes here.

module.exports = table;

表默认使用动态架构。Tables use a dynamic schema by default. 若要全局关闭动态架构,请在 Azure 门户中将 MS_DynamicSchema 应用设置指定为 false。To turn off the dynamic schema globally, set the MS_DynamicSchema app setting to false in the Azure portal.

可以在 GitHub 上的待办事项示例中找到完整示例。You can find a complete example in the todo sample on GitHub.

使用静态架构定义表Define tables by using a static schema

可以将列显式定义为通过 Web API 公开。You can explicitly define the columns to expose via the Web API. azure-mobile-apps Node.js SDK 自动将脱机数据同步所需的任何其他列添加到所提供的列表。The azure-mobile-apps Node.js SDK automatically adds any extra columns required for offline data sync to the list that you provide. 例如,快速入门客户端应用程序需要包含两个列的表:text(字符串)和 complete(布尔值)。For example, the quickstart client applications require a table with two columns: text (a string) and complete (a Boolean).
可以在表定义 JavaScript 文件中(位于 tables 目录中)定义该表,如下所示:The table can be defined in the table definition JavaScript file (located in the tables directory) as follows:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Define the columns within the table.
table.columns = {
    "text": "string",
    "complete": "boolean"
};

// Turn off the dynamic schema.
table.dynamicSchema = false;

module.exports = table;

如果以静态方式定义表,则还必须调用 tables.initialize() 方法,在启动时创建数据库架构。If you define tables statically, you must also call the tables.initialize() method to create the database schema on startup. tables.initialize() 方法返回 Promise,使 Web 服务不会在数据库初始化之前处理请求。The tables.initialize() method returns a promise so that the web service does not serve requests before the database is initialized.

使用 SQL Server Express 作为本地计算机上的开发数据存储Use SQL Server Express as a development data store on your local machine

移动应用 Node.js SDK 提供三种现成可用的数据提供选项:The Mobile Apps Node.js SDK provides three options for serving data out of the box:

  • 使用内存驱动程序提供非持久性示例存储。Use the memory driver to provide a non-persistent example store.
  • 使用 mssql 驱动程序提供可供开发使用的 SQL Server Express 数据存储。Use the mssql driver to provide a SQL Server Express data store for development.
  • 使用 mssql 驱动程序提供可供生产使用的 Azure SQL 数据库数据存储。Use the mssql driver to provide an Azure SQL Database data store for production.

移动应用 Node.js SDK 利用 mssql Node.js 包来建立和使用 SQL Server Express 与 SQL 数据库的连接。The Mobile Apps Node.js SDK uses the mssql Node.js package to establish and use a connection to both SQL Server Express and SQL Database. 若要使用此包,需要在 SQL Server Express 实例上启用 TCP 连接。This package requires that you enable TCP connections on your SQL Server Express instance.

Tip

内存驱动程序不提供完整的测试工具集。The memory driver does not provide a complete set of facilities for testing. 若要在本地测试后端,建议使用 SQL Server Express 数据存储和 mssql 驱动程序。If you want to test your back end locally, we recommend the use of a SQL Server Express data store and the mssql driver.

  1. 下载并安装 Microsoft SQL Server 2014 ExpressDownload and install Microsoft SQL Server 2014 Express. 请务必安装 SQL Server 2014 Express with Tools 版。Ensure that you install the SQL Server 2014 Express with Tools edition. 除非确实需要 64 位支持,否则请使用 32 位版本,因为它在运行时消耗的内存更少。Unless you explicitly require 64-bit support, the 32-bit version consumes less memory when running.

  2. 运行 SQL Server 2014 配置管理器:Run SQL Server 2014 Configuration Manager:

    a.a. 在树菜单中,展开“SQL Server 网络配置” 节点。Expand the SQL Server Network Configuration node in the tree menu.

    b.b. 选择“SQLEXPRESS 的协议” 。Select Protocols for SQLEXPRESS.

    c.c. 右键单击“TCP/IP” ,然后选择“启用” 。Right-click TCP/IP and select Enable. 在弹出对话框中选择“确定” 。Select OK in the pop-up dialog box.

    d.d. 右键单击“TCP/IP” ,然后选择“属性” 。Right-click TCP/IP and select Properties.

    e.e. 选择“IP 地址” 选项卡。Select the IP Addresses tab.

    f.f. 找到“IPAll” 节点。Find the IPAll node. 在“TCP 端口” 字段中输入 1433 。In the TCP Port field, enter 1433.

    配置 SQL Server Express 的 TCP/IP

    g.g. 选择“确定” 。Select OK. 在弹出对话框中选择“确定” 。Select OK in the pop-up dialog box.

    h.如果该值不存在,请单击“添加行”。h. 在树菜单中,选择“SQL Server 服务” 。Select SQL Server Services in the tree menu.

    i.i. 右键单击 SQL Server (SQLEXPRESS) ,并选择“重启” 。Right-click SQL Server (SQLEXPRESS) and select Restart.

    j.j. 关闭 SQL Server 2014 配置管理器。Close SQL Server 2014 Configuration Manager.

  3. 运行 SQL Server 2014 Management Studio 并连接到本地 SQL Server Express 实例:Run SQL Server 2014 Management Studio and connect to your local SQL Server Express instance:

    1. 在对象资源管理器中右键单击实例,并选择“属性” 。Right-click your instance in Object Explorer and select Properties.

    2. 选择“安全性” 页。Select the Security page.

    3. 确保已选择“SQL Server 和 Windows 身份验证模式” 。Ensure that SQL Server and Windows Authentication mode is selected.

    4. 选择“确定” 。Select OK.

      配置 SQL Server Express 身份验证

    5. 在对象资源管理器中展开“安全性” > “登录” 。Expand Security > Logins in Object Explorer.

    6. 右键单击“登录” ,并选择“新建登录名” 。Right-click Logins and select New Login.

    7. 输入登录名。Enter a login name. 选择“SQL Server 身份验证” 。Select SQL Server authentication. 输入密码,并在“确认密码” 中输入相同的密码。Enter a password, and then enter the same password in Confirm password. 密码必须符合 Windows 复杂性要求。The password must meet Windows complexity requirements.

    8. 选择“确定” 。Select OK.

      向 SQL Server Express 添加新用户

    9. 右键单击新登录名并选择“属性” 。Right-click your new login and select Properties.

    10. 选择“服务器角色” 页。Select the Server Roles page.

    11. 选中 dbcreator 服务器角色旁边的复选框。Select the check box for the dbcreator server role.

    12. 选择“确定” 。Select OK.

    13. 关闭 SQL Server 2015 Management Studio。Close SQL Server 2015 Management Studio.

请务必记下选择的用户名和密码。Be sure to record the username and password that you selected. 可能需要根据数据库要求分配其他服务器角色或权限。You might need to assign additional server roles or permissions, depending on your database requirements.

Node.js 应用程序将读取 SQLCONNSTR_MS_TableConnectionString 环境变量,以读取此数据库的连接字符串。The Node.js application reads the SQLCONNSTR_MS_TableConnectionString environment variable for the connection string for this database. 可以在环境中设置此变量。You can set this variable in your environment. 例如,可以使用 PowerShell 设置此环境变量:For example, you can use PowerShell to set this environment variable:

$env:SQLCONNSTR_MS_TableConnectionString = "Server=127.0.0.1; Database=mytestdatabase; User Id=azuremobile; Password=T3stPa55word;"

通过 TCP/IP 连接访问数据库。Access the database through a TCP/IP connection. 提供连接的用户名和密码。Provide a username and password for the connection.

配置项目以进行本地开发Configure your project for local development

移动应用从本地文件系统读取名为 azureMobile.js 的 JavaScript 文件。Mobile Apps reads a JavaScript file called azureMobile.js from the local file system. 不要使用此文件在生产环境中配置移动应用 SDK。Do not use this file to configure the Mobile Apps SDK in production. 请改用 Azure 门户中的“应用设置” 。Instead, use App settings in the Azure portal.

azureMobile.js 文件应导出配置对象。The azureMobile.js file should export a configuration object. 最常见的设置如下:The most common settings are:

  • 数据库设置Database settings
  • 诊断日志记录设置Diagnostic logging settings
  • 备用 CORS 设置Alternate CORS settings

以下示例 azureMobile.js 文件实现上述数据库设置:This example azureMobile.js file implements the preceding database settings:

module.exports = {
    cors: {
        origins: [ 'localhost' ]
    },
    data: {
        provider: 'mssql',
        server: '127.0.0.1',
        database: 'mytestdatabase',
        user: 'azuremobile',
        password: 'T3stPa55word'
    },
    logging: {
        level: 'verbose'
    }
};

建议将 azureMobile.js 添加到 .gitignore 文件(或其他源代码管理 ignore 文件),防止将密码存储在云中 。We recommend that you add azureMobile.js to your .gitignore file (or other source code control ignore file) to prevent passwords from being stored in the cloud. 始终在 Azure 门户中的“应用设置”内配置生产设置 。Always configure production settings in App settings within the Azure portal.

配置移动应用的应用设置Configure app settings for your mobile app

azureMobile.js 文件中的大多数设置在 Azure 门户中都有对等的应用设置。Most settings in the azureMobile.js file have an equivalent app setting in the Azure portal. 使用以下列表在“应用设置”中配置应用 :Use the following list to configure your app in App settings:

应用设置App setting azureMobile.js 设置azureMobile.js setting 说明Description 有效值Valid values
MS_MobileAppName MS_MobileAppName namename 应用的名称Name of the app stringstring
MS_MobileLoggingLevel MS_MobileLoggingLevel logging.levellogging.level 要记录的消息的最小日志级别Minimum log level of messages to log error、warning、info、verbose、debug、sillyerror, warning, info, verbose, debug, silly
MS_DebugMode MS_DebugMode debugdebug 启用或禁用调试模式Enables or disables debug mode true、falsetrue, false
MS_TableSchema MS_TableSchema data.schemadata.schema SQL 表的默认架构名称Default schema name for SQL tables 字符串(默认值:dbo)string (default: dbo)
MS_DynamicSchema MS_DynamicSchema data.dynamicSchemadata.dynamicSchema 启用或禁用调试模式Enables or disables debug mode true、falsetrue, false
MS_DisableVersionHeader MS_DisableVersionHeader 版本(设置为 undefined)version (set to undefined) 禁用 X-ZUMO-Server-Version 标头Disables the X-ZUMO-Server-Version header true、falsetrue, false
MS_SkipVersionCheck MS_SkipVersionCheck skipversioncheckskipversioncheck 禁用客户端 API 版本检查Disables the client API version check true、falsetrue, false

若要指定某项应用设置,请执行以下操作:To set an app setting:

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 选择“所有资源” 或“应用服务” ,并选择移动应用的名称。Select All resources or App Services, and then select the name of your mobile app.
  3. 默认会打开“设置”窗格 。The Settings pane opens by default. 如果没有打开,请选择“设置” 。If it doesn't, select Settings.
  4. 在“常规”菜单中,选择“应用程序设置” 。On the GENERAL menu, select Application settings.
  5. 滚动到“应用设置”部分 。Scroll to the App settings section.
  6. 如果该应用设置已存在,请选择其值进行编辑。If your app setting already exists, select the value of the app setting to edit the value. 如果该应用设置不存在,请在“键”框中输入“应用设置”,在“值”框中输入值 。If your app setting does not exist, enter the app setting in the Key box and the value in the Value box.
  7. 选择“其他安全性验证” 。Select Save.

更改大多数应用设置后都需要重启服务。Changing most app settings requires a service restart.

使用 SQL 数据库作为生产数据存储Use SQL Database as your production data store

无论使用哪种 Azure 应用服务应用程序类型,将 Azure SQL 数据库用作数据存储的过程都是相同的。Using Azure SQL Database as a data store is identical across all Azure App Service application types. 如果尚未这样做,请根据以下步骤创建移动应用后端:If you have not done so already, follow these steps to create a Mobile Apps back end:

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 在窗口左上方,选择“+新建” 按钮 >“Web + 移动” >“移动应用” ,并为移动应用后端提供名称。In the upper left of the window, select the +NEW button > Web + Mobile > Mobile App, and then provide a name for your Mobile Apps back end.

  3. 在“资源组” 框中,输入与应用相同的名称。In the Resource Group box, enter the same name as your app.

  4. 系统将选择默认应用服务计划。The default App Service plan is selected. 若要更改应用服务计划:If you want to change your App Service plan:

    a.a. 选择“应用服务计划” > “+ 新建”。Select App Service Plan > +Create New.

    b.b. 提供新应用服务计划的名称并选择适当的位置。Provide a name of the new App Service plan and select an appropriate location.

    c.c. 选择适当的服务定价层。Select an appropriate pricing tier for the service. 选择“全部查看” 以查看其他定价选项,例如“免费” 和“共享” 。Select View all to view more pricing options, such as Free and Shared.

    d.d. 单击“选择”按钮。 Click the Select button.

    e.e. 返回“应用服务计划”窗格,选择“确定”。 Back in the App Service plan pane, select OK.

  5. 选择“创建” 。Select Create.

预配移动应用后端可能需要几分钟时间。Provisioning a Mobile Apps back end can take a couple of minutes. 预配移动应用后端后,门户将打开移动应用后端的“设置” 窗格。After the Mobile Apps back end is provisioned, the portal opens the Settings pane for the Mobile Apps back end.

可以选择将现有的 SQL 数据库连接到移动应用后端,或创建新的 SQL 数据库。You can choose to either connect an existing SQL database to your Mobile Apps back end or create a new SQL database. 本部分创建 SQL 数据库。In this section, we create a SQL database.

Note

如果在与移动应用后端相同的位置已有一个数据库,则可以选择“使用现有数据库” ,并选择该数据库。If you already have a database in the same location as the Mobile Apps back end, you can instead select Use an existing database and then select that database. 不建议使用位于不同位置的数据库,因为延迟更高。We don't recommend the use of a database in a different location because of higher latencies.

  1. 在新移动应用后端中,选择“设置” > “移动应用” > “数据” > “+添加” 。In the new Mobile Apps back end, select Settings > Mobile App > Data > +Add.

  2. 在“添加数据连接” 窗格中,选择“SQL 数据库 - 配置所需的设置” > “创建新数据库” 。In the Add data connection pane, select SQL Database - Configure required settings > Create a new database. 在“名称” 框中输入新数据库的名称。Enter the name of the new database in the Name box.

  3. 选择“服务器”。 Select Server. 在“新建服务器” 窗格中的“服务器名称” 框内输入唯一的服务器名称,并提供合适的服务器管理员登录名和密码。In the New server pane, enter a unique server name in the Server name box, and provide a suitable server admin login and password. 请确保选中“允许 Azure 服务访问服务器” 。Ensure that Allow azure services to access server is selected. 选择“确定” 。Select OK.

    创建 Azure SQL 数据库

  4. 在“新建数据库”窗格中,选择“确定”。 In the New database pane, select OK.

  5. 返回“添加数据连接”窗格,选择“连接字符串”,并输入创建数据库时提供的登录名与密码。 Back in the Add data connection pane, select Connection string, and enter the login and password that you provided when you created the database. 如果使用现有数据库,请提供该数据库的登录凭据。If you use an existing database, provide the login credentials for that database. 选择“确定” 。Select OK.

  6. 再次返回“添加数据连接”窗格,选择“确定”创建数据库。 Back in the Add data connection pane again, select OK to create the database.

创建数据库可能需要几分钟时间。Creation of the database can take a few minutes. 使用“通知” 区域可监视部署进度。Use the Notifications area to monitor the progress of the deployment. 在数据库成功部署之前,请不要继续操作。Do not progress until the database is deployed successfully. 部署数据库后,会在移动应用后端的应用设置中创建 SQL 数据库实例的连接字符串。After the database is deployed, a connection string is created for the SQL Database instance in your Mobile Apps back-end app settings. 可以在“设置” > “应用程序设置” > “连接字符串” 中查看此应用设置。You can see this app setting in Settings > Application settings > Connection strings.

要求在访问表时进行身份验证Require authentication for access to tables

若要对 tables 终结点使用应用服务身份验证,必须先在 Azure 门户中配置应用服务身份验证。If you want to use App Service Authentication with the tables endpoint, you must configure App Service Authentication in the Azure portal first. 有关详细信息,请参阅要使用的标识提供者的配置指南:For more information, see the configuration guide for the identity provider that you intend to use:

每个表都有一个访问属性用于控制对表的访问。Each table has an access property that you can use to control access to the table. 以下示例显示了以静态方式定义的、要求身份验证的表。The following sample shows a statically defined table with authentication required.

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Define the columns within the table.
table.columns = {
    "text": "string",
    "complete": "boolean"
};

// Turn off the dynamic schema.
table.dynamicSchema = false;

// Require authentication to access the table.
table.access = 'authenticated';

module.exports = table;

访问属性可接受三个值中的一个:The access property can take one of three values:

  • anonymous 表示允许客户端应用程序未经身份验证即可读取数据。anonymous indicates that the client application is allowed to read data without authentication.
  • authenticated 表示客户端应用程序必须随请求发送有效的身份验证令牌。authenticated indicates that the client application must send a valid authentication token with the request.
  • disabled 表示此表当前已禁用。disabled indicates that this table is currently disabled.

如果未定义访问属性,则允许未经身份验证的访问。If the access property is undefined, unauthenticated access is allowed.

对表使用身份验证声明Use authentication claims with your tables

可以设置各种声明,在设置身份验证时会请求这些声明。You can set up various claims that are requested when authentication is set up. 这些声明通常无法通过 context.user 对象获取。These claims are not normally available through the context.user object. 但是,可以使用 context.user.getIdentity() 方法来检索它们。However, you can retrieve them by using the context.user.getIdentity() method. getIdentity() 方法返回可解析成某个对象的 Promise。The getIdentity() method returns a promise that resolves to an object. 该对象由身份验证方法(microsoftaccount 或 aad)进行键控。The object is keyed by the authentication method (microsoftaccount, or aad).

例如,如果设置 Microsoft 帐户身份验证并请求电子邮件地址声明,可以使用以下表控制器将电子邮件地址添加到记录:For example, if you set up Microsoft account authentication and request the email addresses claim, you can add the email address to the record with the following table controller:

var azureMobileApps = require('azure-mobile-apps');

// Create a new table definition.
var table = azureMobileApps.table();

table.columns = {
    "emailAddress": "string",
    "text": "string",
    "complete": "boolean"
};
table.dynamicSchema = false;
table.access = 'authenticated';

/**
* Limit the context query to those records with the authenticated user email address
* @param {Context} context the operation context
* @returns {Promise} context execution Promise
*/
function queryContextForEmail(context) {
    return context.user.getIdentity().then((data) => {
        context.query.where({ emailAddress: data.microsoftaccount.claims.emailaddress });
        return context.execute();
    });
}

/**
* Adds the email address from the claims to the context item - used for
* insert operations
* @param {Context} context the operation context
* @returns {Promise} context execution Promise
*/
function addEmailToContext(context) {
    return context.user.getIdentity().then((data) => {
        context.item.emailAddress = data.microsoftaccount.claims.emailaddress;
        return context.execute();
    });
}

// Configure specific code when the client does a request.
// READ: only return records that belong to the authenticated user.
table.read(queryContextForEmail);

// CREATE: add or overwrite the userId based on the authenticated user.
table.insert(addEmailToContext);

// UPDATE: only allow updating of records that belong to the authenticated user.
table.update(queryContextForEmail);

// DELETE: only allow deletion of records that belong to the authenticated user.
table.delete(queryContextForEmail);

module.exports = table;

若要查看哪些声明可用,请使用 Web 浏览器查看站点的 /.auth/me 终结点。To see what claims are available, use a web browser to view the /.auth/me endpoint of your site.

禁用对特定表操作的访问Disable access to specific table operations

除了出现在表上以外,访问属性还可用于控制单个操作。In addition to appearing on the table, the access property can be used to control individual operations. 共有四项操作:There are four operations:

  • read 是对表运行的 RESTful GET 操作。read is the RESTful GET operation on the table.
  • insert 是对表运行的 RESTful POST 操作。insert is the RESTful POST operation on the table.
  • update 是对表运行的 RESTful PATCH 操作。update is the RESTful PATCH operation on the table.
  • delete 是对表运行的 RESTful DELETE 操作。delete is the RESTful DELETE operation on the table.

例如,若要提供未经身份验证的只读表:For example, you might want to provide a read-only unauthenticated table:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Read-only table. Only allow READ operations.
table.read.access = 'anonymous';
table.insert.access = 'disabled';
table.update.access = 'disabled';
table.delete.access = 'disabled';

module.exports = table;

调整与表操作配合使用的查询Adjust the query that is used with table operations

表操作的常见要求是提供受限制的数据视图。A common requirement for table operations is to provide a restricted view of the data. 例如,可以提供标有已经过身份验证的用户 ID 的表,以便只有你能够读取或更新自己的记录。For example, you can provide a table that is tagged with the authenticated user ID such that you can only read or update your own records. 以下表定义将提供此功能:The following table definition provides this functionality:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Define a static schema for the table.
table.columns = {
    "userId": "string",
    "text": "string",
    "complete": "boolean"
};
table.dynamicSchema = false;

// Require authentication for this table.
table.access = 'authenticated';

// Ensure that only records for the authenticated user are retrieved.
table.read(function (context) {
    context.query.where({ userId: context.user.id });
    return context.execute();
});

// When adding records, add or overwrite the userId with the authenticated user.
table.insert(function (context) {
    context.item.userId = context.user.id;
    return context.execute();
});

module.exports = table;

正常运行查询的操作包含一个可以使用 where 子句进行调整的查询属性。Operations that normally run a query have a query property that you can adjust by using a where clause. 该查询属性是一个 QueryJS 对象,用于将 OData 查询转换成数据后端可以处理的某种形式。The query property is a QueryJS object that is used to convert an OData query to something that the data back end can process. 在简单的相等性比较方案中(如上例),可以使用映射。For simple equality cases (like the preceding one), you can use a map. 也可添加特定的 SQL 子句:You can also add specific SQL clauses:

context.query.where('myfield eq ?', 'value');

在表中配置软删除Configure a soft delete on a table

软删除并不实际删除记录。A soft delete does not actually delete records. 它将已删除的列设置为 true,将记录标记为已在数据库中删除。Instead it marks them as deleted within the database by setting the deleted column to true. 移动应用 SDK 自动从结果中删除已软删除的记录,除非 Mobile Client SDK 使用 IncludeDeleted()The Mobile Apps SDK automatically removes soft-deleted records from results unless the Mobile Client SDK uses IncludeDeleted(). 若要为表配置软删除,请在表定义文件中设置 softDelete 属性:To configure a table for a soft delete, set the softDelete property in the table definition file:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Define the columns within the table.
table.columns = {
    "text": "string",
    "complete": "boolean"
};

// Turn off the dynamic schema.
table.dynamicSchema = false;

// Turn on soft delete.
table.softDelete = true;

// Require authentication to access the table.
table.access = 'authenticated';

module.exports = table;

应该建立记录删除机制:客户端应用程序、Web 作业、Azure 函数或自定义 API。You should establish a mechanism for deleting records: a client application, a WebJob, an Azure function, or a custom API.

在数据库中植入数据Seed your database with data

创建新应用程序时,可能需要在表中植入数据。When you're creating a new application, you might want to seed a table with data. 可在表定义 JavaScript 文件中实现此目的,如下所示:You can do this within the table definition JavaScript file as follows:

var azureMobileApps = require('azure-mobile-apps');

var table = azureMobileApps.table();

// Define the columns within the table.
table.columns = {
    "text": "string",
    "complete": "boolean"
};
table.seed = [
    { text: 'Example 1', complete: false },
    { text: 'Example 2', complete: true }
];

// Turn off the dynamic schema.
table.dynamicSchema = false;

// Require authentication to access the table.
table.access = 'authenticated';

module.exports = table;

仅当表是由移动应用 SDK 创建时,才能植入数据。Seeding of data happens only when you've used the Mobile Apps SDK to create the table. 如果表已在数据库中,则不会在表中注入任何数据。If the table already exists in the database, no data is injected into the table. 如果打开了动态架构,将从植入的数据推断架构。If the dynamic schema is turned on, the schema is inferred from the seeded data.

建议显式调用 tables.initialize() 方法,在服务开始运行时创建表。We recommend that you explicitly call the tables.initialize() method to create the table when the service starts running.

启用 Swagger 支持Enable Swagger support

移动应用随附内置的 Swagger 支持。Mobile Apps comes with built-in Swagger support. 若要启用 Swagger 支持,请先安装 swagger-ui 作为依赖项:To enable Swagger support, first install swagger-ui as a dependency:

npm install --save swagger-ui

然后,可以在移动应用构造函数中启用 Swagger 支持:You can then enable Swagger support in the Mobile Apps constructor:

var mobile = azureMobileApps({ swagger: true });

可能只想要在开发版本中启用 Swagger 支持。You probably only want to enable Swagger support in development editions. 为此,可以使用 NODE_ENV 应用设置:You can do this by using the NODE_ENV app setting:

var mobile = azureMobileApps({ swagger: process.env.NODE_ENV !== 'production' });

swagger 终结点位于 http://你的站点.chinacloudsites.cn/swagger。The swagger endpoint is located at http://yoursite.chinacloudsites.cn/swagger. 可通过 /swagger/ui 终结点访问 Swagger UI。You can access the Swagger UI via the /swagger/ui endpoint. 如果选择要求在整个应用程序中进行身份验证,Swagger 将生成错误。If you choose to require authentication across your entire application, Swagger produces an error. 为获得最佳效果,请在“Azure 应用服务身份验证/授权”设置中选择允许未经身份验证的请求通过,并使用 table.access 属性控制身份验证。For best results, choose to allow unauthenticated requests in the Azure App Service Authentication/Authorization settings, and then control authentication by using the table.access property.

如果希望只在本地进行开发时才使用 Swagger 支持,则也可以将 Swagger 选项添加到 azureMobile.js 文件中。You can also add the Swagger option to your azureMobile.js file if you only want Swagger support for developing locally.

推送通知Push notifications

移动应用与 Azure 通知中心集成,因此,我们可以跨所有主要平台向数百万台设备发送有针对性的推送通知。Mobile Apps integrates with Azure Notification Hubs so you can send targeted push notifications to millions of devices across all major platforms. 使用通知中心可将推送通知发送到 iOS、Android 和 Windows 设备。By using Notification Hubs, you can send push notifications to iOS, Android, and Windows devices. 若要详细了解通知中心的所有功能,请参阅通知中心概述To learn more about all that you can do with Notification Hubs, see the Notification Hubs overview.

发送推送通知Send push notifications

以下代码演示如何使用 push 对象向已注册的 iOS 设备发送广播推送通知:The following code shows how to use the push object to send a broadcast push notification to registered iOS devices:

// Create an APNS payload.
var payload = '{"aps": {"alert": "This is an APNS payload."}}';

// Only do the push if configured.
if (context.push) {
    // Send a push notification by using APNS.
    context.push.apns.send(null, payload, function (error) {
        if (error) {
            // Do something or log the error.
        }
    });
}

通过从客户端创建模板推送注册,可以改为向所有受支持平台上的设备发送模板推送消息。By creating a template push registration from the client, you can instead send a template push message to devices on all supported platforms. 以下代码演示如何发送模板通知:The following code shows how to send a template notification:

// Define the template payload.
var payload = '{"messageParam": "This is a template payload."}';

// Only do the push if configured.
if (context.push) {
    // Send a template notification.
    context.push.send(null, payload, function (error) {
        if (error) {
            // Do something or log the error.
        }
    });
}

使用标记将推送通知发送到经过身份验证的用户Send push notifications to an authenticated user by using tags

当经过身份验证的用户注册推送通知时,用户 ID 标记自动添加到注册中。When an authenticated user registers for push notifications, a user ID tag is automatically added to the registration. 使用此标记可以向特定用户注册的所有设备发送推送通知。By using this tag, you can send push notifications to all devices registered by a specific user. 以下代码获取发出请求的用户的 SID,并将模板推送通知发送到该用户的每个设备注册:The following code gets the SID of user who's making the request and sends a template push notification to every device registration for that user:

// Only do the push if configured.
if (context.push) {
    // Send a notification to the current user.
    context.push.send(context.user.id, payload, function (error) {
        if (error) {
            // Do something or log the error.
        }
    });
}

在注册来自经过身份验证客户端的推送通知时,请确保在尝试注册之前身份验证已完成。When you're registering for push notifications from an authenticated client, make sure that authentication is complete before you attempt registration.

自定义 APICustom APIs

定义自定义 APIDefine a custom API

除了通过 /tables 终结点的数据访问 API 以外,移动应用还可提供自定义 API 覆盖范围。In addition to the Data Access API via the /tables endpoint, Mobile Apps can provide custom API coverage. 自定义 API 以类似于表定义的方法定义,可访问所有相同的功能,包括身份验证。Custom APIs are defined in a similar way to the table definitions and can access all the same facilities, including authentication.

若要将应用服务身份验证与自定义 API 配合使用,必须先在 Azure 门户中配置应用服务身份验证。If you want to use App Service Authentication with a custom API, you must configure App Service Authentication in the Azure portal first. 有关详细信息,请参阅要使用的标识提供者的配置指南:For more information, see the configuration guide for the identity provider that you intend to use:

定义自定义 API 的方法与表 API 大致相同:Custom APIs are defined in much the same way as the Tables API:

  1. 创建 api 目录。Create an api directory.
  2. api 目录中创建 API 定义 JavaScript 文件。Create an API definition JavaScript file in the api directory.
  3. 使用 import 方法导入 api 目录。Use the import method to import the api directory.

下面是根据前面使用的基本应用示例所做的原型 API 定义:Here is the prototype API definition based on the basic-app sample that we used earlier:

var express = require('express'),
    azureMobileApps = require('azure-mobile-apps');

var app = express(),
    mobile = azureMobileApps();

// Import the custom API.
mobile.api.import('./api');

// Add the Mobile API so it is accessible as a Web API.
app.use(mobile);

// Start listening on HTTP
app.listen(process.env.PORT || 3000);

让我们使用一个通过 Date.now() 方法返回服务器日期的示例 API。Let's take an example API that returns the server date by using the Date.now() method. 下面是 api/date.js 文件:Here is the api/date.js file:

var api = {
    get: function (req, res, next) {
        var date = { currentTime: Date.now() };
        res.status(200).type('application/json').send(date);
    });
};

module.exports = api;

每个参数是标准的 RESTful 谓词之一:GET、POST、PATCH 或 DELETE。Each parameter is one of the standard RESTful verbs: GET, POST, PATCH, or DELETE. 此方法是发送所需输出的标准 ExpressJS 中间件函数。The method is a standard ExpressJS middleware function that sends the required output.

要求在访问自定义 API 时进行身份验证Require authentication for access to a custom API

Azure 移动应用 SDK 对 tables 终结点和自定义 API 使用相同的方式实现身份验证。The Mobile Apps SDK implements authentication in the same way for both the tables endpoint and custom APIs. 若要在前一部分开发的 API 中添加身份验证,请添加 access 属性:To add authentication to the API developed in the previous section, add an access property:

var api = {
    get: function (req, res, next) {
        var date = { currentTime: Date.now() };
        res.status(200).type('application/json').send(date);
    });
};
// All methods must be authenticated.
api.access = 'authenticated';

module.exports = api;

也可以指定对特定操作的身份验证:You can also specify authentication on specific operations:

var api = {
    get: function (req, res, next) {
        var date = { currentTime: Date.now() };
        res.status(200).type('application/json').send(date);
    }
};
// The GET methods must be authenticated.
api.get.access = 'authenticated';

module.exports = api;

对于要求身份验证的自定义 API,必须使用与 tables 终结点相同的令牌。The same token that is used for the tables endpoint must be used for custom APIs that require authentication.

处理大型文件上传Handle large file uploads

移动应用 SDK 使用正文分析器中间件来接受和解码提交件的正文内容。The Mobile Apps SDK uses the body-parser middleware to accept and decode body content in your submission. 可以将正文分析器预先配置为接受大型文件上传:You can preconfigure body-parser to accept larger file uploads:

var express = require('express'),
    bodyParser = require('body-parser'),
    azureMobileApps = require('azure-mobile-apps');

var app = express(),
    mobile = azureMobileApps();

// Set up large body content handling.
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

// Import the custom API.
mobile.api.import('./api');

// Add the Mobile API so it is accessible as a Web API.
app.use(mobile);

// Start listening on HTTP.
app.listen(process.env.PORT || 3000);

传输前,该文件采用 Base-64 编码。The file is base-64 encoded before transmission. 此编码会增加实际上传的大小(因此必须考虑该大小)。This encoding increases the size of the actual upload (and the size that you must account for).

执行自定义 SQL 语句Execute custom SQL statements

移动应用 SDK 允许通过请求对象访问整个上下文。The Mobile Apps SDK allows access to the entire context through the request object. 可以轻松针对定义的数据提供程序执行参数化的 SQL 语句:You can easily execute parameterized SQL statements to the defined data provider:

var api = {
    get: function (request, response, next) {
        // Check for parameters. If not there, pass on to a later API call.
        if (typeof request.params.completed === 'undefined')
            return next();

        // Define the query. Anything that the mssql
        // driver can handle is allowed.
        var query = {
            sql: 'UPDATE TodoItem SET complete=@completed',
            parameters: [{
                completed: request.params.completed
            }]
        };

        // Execute the query. The context for Mobile Apps is available through
        // request.azureMobile. The data object contains the configured data provider.
        request.azureMobile.data.execute(query)
        .then(function (results) {
            response.json(results);
        });
    }
};

api.get.access = 'authenticated';
module.exports = api;

调试Debugging

对移动应用进行调试、诊断和故障排除Debug, diagnose, and troubleshoot Mobile Apps

Azure 应用服务提供多种适用于 Node.js 应用程序的调试和故障排除方法。Azure App Service provides several debugging and troubleshooting techniques for Node.js applications. 若要开始针对 Node.js 移动应用后端进行故障排除,请参阅以下文章:To get started in troubleshooting your Node.js Mobile Apps back end, see the following articles:

Node.js 应用程序可访问各种诊断日志工具。Node.js applications have access to a wide range of diagnostic log tools. 在内部,移动应用 Node.js SDK 使用 Winston 进行诊断日志记录。Internally, the Mobile Apps Node.js SDK uses Winston for diagnostic logging. 启用调试模式,或者在 Azure 门户中将 MS_DebugMode 应用设置指定为 true,即可自动启用日志记录。Logging is automatically enabled when you enable debug mode or set the MS_DebugMode app setting to true in the Azure portal. 生成的日志显示在 Azure 门户上的诊断日志中。Generated logs appear in the diagnostic logs in the Azure portal.