如何使用適用於 Azure Mobile Apps 的 Apache Cordova 用戶端程式庫

概觀

本指南說明如何使用最新的 適用於 Azure Mobile Apps 的 Apache Cordova 外掛程式執行一般案例。 如果您是 Azure Mobile Apps 的新手,請先完成 Azure Mobile Apps 快速啟動 以建立後端、建立資料表及下載預先建置的 Apache Cordova 專案。 在本指南中,我們會著重於用戶端 Apache Cordova 外掛程式。

支援的平台

此 SDK 可在 iOS、Android 和 Windows 裝置上支援 Apache Cordova v6.0.0 和更新版本。 平台支援如下︰

  • Android API 19-24 (KitKat 至 Nougat)。
  • iOS 8.0 版和更新版本。
  • Windows Phone 8.1。
  • 通用 Windows 平台。

設定和必要條件

本指南假設您已建立包含資料表的後端。 本指南假設資料表的結構描述與這些教學課程中的資料表相同。 本指南也假設您已將 Apache Cordova 外掛程式加入至程式碼。 如果您還沒有這樣做,您可以在命令列將 Apache Cordova 外掛程式新增至您的專案:

cordova plugin add cordova-plugin-ms-azure-mobile-apps

如需有關建立 第一個 Apache Cordova 應用程式的詳細資訊,請參閱其文件。

設定 Ionic v2 應用程式

若要適當地定 Ionic v2 專案,請先建立基本應用程式,並新增 Cordova 外掛程式:

ionic start projectName --v2
cd projectName
ionic plugin add cordova-plugin-ms-azure-mobile-apps

新增下列行到 app.component.ts 以建立用戶端專案:

declare var WindowsAzure: any;
var client = new WindowsAzure.MobileServiceClient("https://yoursite.azurewebsites.net");

您現在可以在瀏覽器中建置並執行專案:

ionic platform add browser
ionic run browser

Azure Mobile Apps Cordova 外掛程式同時支援 Ionic v1 與 v2 應用程式。 只有 Ionic v2 應用程式需要 WindowsAzure 物件的其他宣告。

建立用戶端連接

建立 WindowsAzure.MobileServiceClient 物件來建立用戶端連接。 以您行動應用程式的 URL 取代 appUrl

var client = WindowsAzure.MobileServiceClient(appUrl);

使用資料表

若要存取或更新資料,請建立後端資料表的參考。 以您的資料表名稱取代 tableName

var table = client.getTable(tableName);

只要有資料表參考,就進一步使用資料表進行下列作業︰

操作說明 :查詢資料表參考

取得資料表參考之後,您可以使用它來查詢伺服器上的資料。 您可以使用「類似 LINQ」的語言來撰寫查詢。 若要從資料表傳回所有資料,使用下列程式碼:

/**
 * Process the results that are received by a call to table.read()
 *
 * @param {Object} results the results as a pseudo-array
 * @param {int} results.length the length of the results array
 * @param {Object} results[] the individual results
 */
function success(results) {
   var numItemsRead = results.length;

   for (var i = 0 ; i < results.length ; i++) {
       var row = results[i];
       // Each row is an object - the properties are the columns
   }
}

function failure(error) {
    throw new Error('Error loading data: ', error);
}

table
    .read()
    .then(success, failure);

搭配 results 呼叫 success 函式。 請勿在 success 函式中使用 for (var i in results),因為當使用其他查詢函式時 (例如 .includeTotalCount()),這樣會反覆檢查結果中包含的資訊。

如需 Query 語法的詳細資訊,請參閱 [Query 物件文件]。

篩選伺服器上的資料

您可以在資料表參考上使用 where 子句:

table
    .where({ userId: user.userId, complete: false })
    .read()
    .then(success, failure);

您也可以使用函式來篩選物件。 在此案例中, this 變數會指派給目前篩選的物件。 以下程式碼在功能上等同於先前的範例:

function filterByUserId(currentUserId) {
    return this.userId === currentUserId && this.complete === false;
}

table
    .where(filterByUserId, user.userId)
    .read()
    .then(success, failure);

逐頁查看資料

利用 take()skip() 方法。 例如,如果您想要將資料表分割成 100 列的記錄:

var totalCount = 0, pages = 0;

// Step 1 - get the total number of records
table.includeTotalCount().take(0).read(function (results) {
    totalCount = results.totalCount;
    pages = Math.floor(totalCount/100) + 1;
    loadPage(0);
}, failure);

function loadPage(pageNum) {
    let skip = pageNum * 100;
    table.skip(skip).take(100).read(function (results) {
        for (var i = 0 ; i < results.length ; i++) {
            var row = results[i];
            // Process each row
        }
    }
}

.includeTotalCount() 方法是用來將 totalCount 欄位加入至 results 物件。 totalCount 欄位中填入未使用分頁時會傳回的記錄總數。

接著,您可以使用 pages 變數和一些 UI 按鈕來提供頁面清單。您可以使用 loadPage() 載入每個頁面的新記錄。 實作快取來加速存取已經載入的記錄。

操作說明:傳回已排序的資料

使用 .orderBy().orderByDescending() 查詢方法︰

table
    .orderBy('name')
    .read()
    .then(success, failure);

如需 Query 物件的詳細資訊,請參閱 [Query 物件文件]。

操作說明:插入資料

以適當的日期建立 JavaScript 物件,並以非同步方式呼叫 table.insert()

var newItem = {
    name: 'My Name',
    signupDate: new Date()
};

table
    .insert(newItem)
    .done(function (insertedItem) {
        var id = insertedItem.id;
    }, failure);

在成功插入時,插入的項目及同步處理作業所需的其他欄位會一起傳回。 以這項資訊更新您自己的快取,後續更新時才會正確。

Azure Mobile Apps Node.js Server SDK 支援的動態結構描述適用於開發用途。 動態結構描述可讓您在插入或更新作業中指定資料行,以將資料行新增至資料表。 在將應用程式移至生產環境之前,我們建議您關閉動態結構描述。

操作說明:修改資料

類似於 .insert() 方法,您應該建立 Update 物件,然後呼叫 .update()。 Update 物件必須包含要更新的記錄的識別碼 - 在讀取記錄或呼叫 .insert() 時會取得此識別碼。

var updateItem = {
    id: '7163bc7a-70b2-4dde-98e9-8818969611bd',
    name: 'My New Name'
};

table
    .update(updateItem)
    .done(function (updatedItem) {
        // You can now update your cached copy
    }, failure);

操作說明:刪除資料

若要刪除記錄時,請呼叫 .del() 方法。 將識別碼傳入物件參考中:

table
    .del({ id: '7163bc7a-70b2-4dde-98e9-8818969611bd' })
    .done(function () {
        // Record is now deleted - update your cache
    }, failure);

如何:驗證使用者

Azure App Service 支援使用各種外部識別提供者 (Facebook、Google、Microsoft 帳戶及 Twitter) 來驗證與授權應用程式使用者。 您可以在資料表上設定權限,以限制僅有通過驗證使用者可以存取特定操作。 您也可以使用通過驗證使用者的身分識別來實作伺服器指令碼中的授權規則。 如需詳細資訊,請參閱開始與驗證教學課程。

在 Apache Cordova 應用程式中使用驗證時,下列 Cordova 外掛程式必須可用:

支援兩個驗證流程:伺服器流程和用戶端流程。 由於伺服器流程採用提供者的 Web 驗證介面,因此所提供的驗證體驗也最為簡單。 用戶端流程依賴提供者專屬的裝置專用 SDK,可以與裝置特有的功能深入整合,例如單一登入。

作法:向提供者驗證 (伺服器流程)

若要讓 Mobile Apps 管理應用程式中的驗證程序,您必須向識別提供者註冊應用程式。 接著在您的 Azure App Service 中,您必須設定提供者所提供的應用程式識別碼和密碼。 如需詳細資訊,請參閱 將驗證新增至您的應用程式教學課程。

註冊識別提供者之後,請以提供者的名稱來呼叫 .login() 方法。 例如,若要以 Facebook 登入,請使用下列程式碼:

client.login("facebook").done(function (results) {
     alert("You are now signed in as: " + results.userId);
}, function (err) {
     alert("Error: " + err);
});

提供者的有效值是 'aad'、'facebook'、'google'、'microsoftaccount' 和 'twitter'。

注意

Google 驗證目前無法透過伺服器流程運作。 若要使用 Google 進行驗證,您必須使用用戶端流程方法

在此情況下,Azure App Service 會管理 OAuth 2.0 驗證流程。 它會顯示所選提供者的登入頁面,並在使用識別提供者成功登入後產生 App Service 驗證權杖。 login 函式完成時會傳回 JSON 物件,此物件會在 userId 和 authenticationToken 欄位中分別顯示使用者識別碼和 App Service 驗證權杖。 您可以快取並重複使用此權杖,直到它到期為止。

作法:向提供者驗證 (用戶端流程)

您的應用程式也可以個別連絡識別提供者,然後將傳回的權杖提供給 App Service 進行驗證。 此用戶端流程可讓您為使用者提供單一登入體驗,或從識別提供者擷取其他使用者資料。

社交驗證基本範例

這個範例會使用 Facebook 用戶端 SDK 進行驗證:

client.login(
     "facebook",
     {"access_token": token})
.done(function (results) {
     alert("You are now signed in as: " + results.userId);
}, function (err) {
     alert("Error: " + err);
});

此範例假設個別提供者 SDK 所提供的權杖儲存在 token 變數中。

作法:取得已驗證使用者的相關資訊

您可以使用 HTTP 呼叫搭配任何 AJAX 程式庫,從 /.auth/me 端點擷取驗證資訊。 請確定您設定 X-ZUMO-AUTH 標頭至您的驗證 Token。 驗證 Token 儲存於 client.currentUser.mobileServiceAuthenticationToken。 例如,若要使用提取 API:

var url = client.applicationUrl + '/.auth/me';
var headers = new Headers();
headers.append('X-ZUMO-AUTH', client.currentUser.mobileServiceAuthenticationToken);
fetch(url, { headers: headers })
    .then(function (data) {
        return data.json()
    }).then(function (user) {
        // The user object contains the claims for the authenticated user
    });

提取可作為 npm 封裝 或從 CDNJS下載瀏覽器。 您也可以使用 jQuery 或另一個 AJAX API 擷取資訊。 系統會以 JSON 物件形式接收資料。

如何:為外部重新導向 url 設定您的行動 App Service。

有數種類型的 Apache Cordova 應用程式會使用回送功能來處理 OAuth UI 流程。 驗證服務預設只知道如何使用您的服務,因此 localhost 上的 OAuth UI 流程會引發問題。 有問題的 OAuth UI 流程範例包括︰

  • Ripple 模擬器。
  • Ionic 的即時重新載入。
  • 在本機執行行動後端
  • 在不同於提供驗證的 Azure App Service 中執行行動後端。

請遵循下列指示來將您的本機設定加入組態︰

  1. 登入 Azure 入口網站

  2. 選取 [所有資源] 或 [應用程式服務],然後按一下行動應用程式的名稱。

  3. 按一下 [工具]

  4. 按一下 [觀察] 功能表中的 [資源總管],然後按一下 [前往]。 新的視窗或索引標籤隨即開啟。

  5. 在左側導覽中,展開網站的 [config]、[authsettings] 節點。

  6. 按一下 [編輯]

  7. 尋找「allowedExternalRedirectUrls」元素。 它可能會設定為 null 或值陣列。 將此值變更為下列值︰

      "allowedExternalRedirectUrls": [
          "https://localhost:3000",
          "https://localhost:3000"
      ],
    

    使用您服務的 URL 來取代 URL。 範例包括 https://localhost:3000 Node.js 範例服務) 的 (,或 https://localhost:4400 Ripple 服務) 的 (。 不過,這些 URL 都是範例 - 您的情況 (包括範例中提及的服務) 可能會有差異。

  8. 按一下螢幕右上角的 [讀/寫] 按鈕。

  9. 按一下綠色 [PUT] 按鈕。

此時即會儲存設定。 在設定完成儲存之前,請勿關閉瀏覽器視窗。 此外,請將這些回送 URL 新增至 App Service 的 CORS 設定:

  1. 登入 Azure 入口網站
  2. 選取 [所有資源] 或 [應用程式服務],然後按一下行動應用程式的名稱。
  3. [設定] 刀鋒視窗隨即自動開啟。 如果沒有,請按一下 [所有設定]
  4. 按一下 API 功能表下方的 [CORS]
  5. 輸入在提供的方塊中輸入您希望加入的 URL,然後按 Enter 鍵。
  6. 視需要輸入其他的 URL。
  7. 按一下 [儲存] 來儲存這些設定。

大約需要 10-15 秒的時間,才能使新的設定生效。

作法:註冊推播通知

安裝 phonegap-plugin-push 來處理推播通知。 在命令列中使用 cordova plugin add 命令,或在 Visual Studio 內透過 Git 外掛程式安裝程式,即可輕鬆新增此外掛程式。 以下在 Apache Cordova 應用程式中的程式碼會為您的裝置註冊推播通知:

var pushOptions = {
    android: {
        senderId: '<from-gcm-console>'
    },
    ios: {
        alert: true,
        badge: true,
        sound: true
    },
    windows: {
    }
};
pushHandler = PushNotification.init(pushOptions);

pushHandler.on('registration', function (data) {
    registrationId = data.registrationId;
    // For cross-platform, you can use the device plugin to determine the device
    // Best is to use device.platform
    var name = 'gcm'; // For android - default
    if (device.platform.toLowerCase() === 'ios')
        name = 'apns';
    if (device.platform.toLowerCase().substring(0, 3) === 'win')
        name = 'wns';
    client.push.register(name, registrationId);
});

pushHandler.on('notification', function (data) {
    // data is an object and is whatever is sent by the PNS - check the format
    // for your particular PNS
});

pushHandler.on('error', function (error) {
    // Handle errors
});

使用通知中樞 SDK 從伺服器傳送推播通知。 永遠不要直接從用戶端傳送推播通知。 這種方式會被用來對通知中樞或 PNS 觸發阻斷服務攻擊。 PNS 可能會因為這類攻擊而禁止您的流量。

詳細資訊

您可以在 API 文件中找到 API 詳細資訊。