> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# NodeJS 快速入門

> 從 npm 安裝 PlayFab Node.js 用戶端程式庫，並從 Node.js 指令碼進行您的第一次 PlayFab API 呼叫以驗證玩家。

# 快速入門：適用於 NodeJS 的 PlayFab 用戶端程式庫

開始使用適用於 NodeJS 的 PlayFab 用戶端程式庫，進行您的第一次 PlayFab API 呼叫並驗證玩家。請依照步驟安裝套件，並試用基本工作的範例程式碼。

## 必要條件

* [PlayFab 開發人員帳戶](https://developer.playfab.com)。如需建立遊戲和尋找 TitleId 的相關資訊，請參閱 [Game Manager 快速入門](/zh-TW/services/playfab/live-service-management/gamemanager/quickstart)。
* [Node.js](https://nodejs.org/en/download/)
* Node 必須位於您的 PATH 環境變數中。如果您使用安裝程式，它可能已為您設定為預設位置：C:/Program Files (x86)/nodejs/

## 設定

下列命令適用於 Windows、macOS 和 Linux。

1. 為您的專案 \{NodeProjLocation} 建立新資料夾：

   `GettingStarted.js`

2. 在您的專案資料夾中開啟命令視窗。

3. 執行下列命令：

   `npm install playfab-sdk --save`

   (請將此視窗保持開啟，稍後您會再次使用它。)

PlayFab 安裝完成！

## 程式碼範例

### 驗證用戶端

本指南提供進行第一次 PlayFab API 呼叫所需的最少步驟，不含任何 GUI 或畫面上的回饋。確認是透過主控台記錄完成的。如需參數和傳回值的詳細資訊，建議您先使用 [Postman 範本](/zh-TW/services/playfab/sdks/postman/postman-quickstart)。

在您慣用的文字編輯器中，依下列方式更新 GettingStarted.js 的內容：

<Note>
  若要查閱此範例中 `loginRequest` 物件的正確格式，請參閱 [LoginWithCustomID](xref:titleid.playfabapi.com.client.authentication.loginwithcustomid) 的 API 參考。
</Note>

```javascript theme={null}
var PlayFab = require("./node_modules/playfab-sdk/Scripts/PlayFab/PlayFab");
var PlayFabClient = require("./node_modules/playfab-sdk/Scripts/PlayFab/PlayFabClient");

function DoExampleLoginWithCustomID() {
    PlayFab.settings.titleId = "144";
    var loginRequest = {
        // Currently, you need to look up the correct format for this object in the API reference for LoginWithCustomID. The Request Headers and Request Body are included as keys and values in the request object.
        TitleId: PlayFab.settings.titleId,
        CustomId: "GettingStartedGuide",
        CreateAccount: true
    };

    // For functions in the Node SDK, the first parameter will be the request object and the second parameter will be the callback function. The callback function executes after the request returns.
    PlayFabClient.LoginWithCustomID(loginRequest, LoginCallback);
}

function LoginCallback(error, result) {
    if (result !== null) {
        console.log("Congratulations, you made your first successful API call!");
    } else if (error !== null) {
        console.log("Something went wrong with your first API call.");
        console.log("Here's some debug information:");
        console.log(CompileErrorReport(error));
    }
}

// This is a utility function we haven't put into the core SDK yet. Feel free to use it.
function CompileErrorReport(error) {
    if (error == null)
        return "";
    var fullErrors = error.errorMessage;
    for (var paramName in error.errorDetails)
        for (var msgIdx in error.errorDetails[paramName])
            fullErrors += "\n" + paramName + ": " + error.errorDetails[paramName][msgIdx];
    return fullErrors;
}

// Kick off the actual login call
DoExampleLoginWithCustomID();
```

## 執行程式碼

1. 在我們於安裝期間開啟的主控台視窗中，執行下列命令：

   `node GettingStarted.js`

   您應該會看到下列文字作為結果：

   "Congratulations, you made your first successful API call!"

現在，您可以開始進行其他 API 呼叫並建置您的遊戲。

如需所有可用用戶端 API 呼叫的清單，請參閱我們的 [PlayFab API 參考](/zh-TW/services/playfab/api-references)文件。

## 解構程式碼

本節會詳細說明 Node 快速入門程式碼的每個部分。

對於 Node SDK，`PlayFabClientSDK` 中的函式是以 HTTP 要求命名的。例如，`LoginWithCustomID` 函式對應的 HTTP 要求也稱為 "LoginWithCustomID"。要求標頭和要求本文會以索引鍵和值的形式封裝在 JavaScript 要求物件中。

* `GettingStarted.js` 的逐行分析
  * `PlayFab.settings.titleId = "xxxx";`
    * 每位 PlayFab 開發人員都會在 Game Manager 中建立遊戲。當您發佈遊戲時，必須將該 TitleId 寫入遊戲程式碼中。這可讓用戶端知道如何存取 PlayFab 中正確的資料。對大多數使用者而言，只要將其視為讓 PlayFab 運作的必要步驟即可。

  * `var loginRequest = { TitleId: PlayFab.settings.titleId, CustomId: "GettingStartedGuide", CreateAccount: true };`
    * 大多數 PlayFab API 方法都需要輸入參數，而這些輸入參數會封裝在要求物件中。
    * 每個 API 方法都需要唯一的要求物件，其中包含選擇性和必要參數的組合。
      * 對於 `LoginWithCustomIDRequest`，有一個必要參數 `CustomId` 可唯一識別玩家，還有 `CreateAccount` 允許透過此呼叫建立新帳戶。`TitleId` 是 JavaScript 中的另一個必要參數，且必須與 `PlayFab.settings.titleId` 相符。
      * 如需在何處尋找 `TitleId` 的相關資訊，請參閱 [Game Manager 快速入門](/zh-TW/services/playfab/live-service-management/gamemanager/quickstart)。
* 在此案例中，`TitleId`、`customId` 和 `CreateAccount` 來自 `LoginWithCustomID` 的要求本文。
  * `PlayFabClientSDK.LoginWithCustomID(loginRequest, LoginCallback);`
    * 這會開始對 `LoginWithCustomID` 的非同步要求，並在 API 呼叫完成時呼叫 LoginCallback。

  * 對於登入，大多數開發人員會想要使用更合適的登入方法。
    * 如需所有登入方法和輸入參數的清單，請參閱 [PlayFab 登入文件](xref:titleid.playfabapi.com.client.authentication)。常見的選擇包括：
      * [LoginWithAndroidDeviceID](xref:titleid.playfabapi.com.client.authentication.loginwithandroiddeviceid)
      * [LoginWithIOSDeviceID](xref:titleid.playfabapi.com.client.authentication.loginwithiosdeviceid)
      * [LoginWithEmailAddress](xref:titleid.playfabapi.com.client.authentication.loginwithemailaddress)
* `LoginCallback` 包含兩個參數：`error` 和 `result`。
  * 成功時，`error` 會是 `null`，而 `result` 物件會根據所呼叫的 API 包含所要求的資訊。
    * 此 `result` 包含玩家的一些基本資訊，但對大多數使用者而言，登入只是呼叫其他 API 之前的必要步驟。
* 如果 error 不是 `null`，表示您的 API 已失敗。

## 疑難排解

* API 呼叫可能因許多原因而失敗，您應該一律嘗試處理失敗情況。
* error 物件包含錯誤名稱、錯誤碼和錯誤訊息。這些資訊加起來應該足以診斷您的錯誤。
* API 呼叫失敗的原因 (依可能性排序)：
  * 未設定 `PlayFabSettings.TitleId`。如果您忘記將 `TitleId` 設定為您的遊戲，則一切都無法運作。
  * 要求參數。如果您沒有為特定 API 呼叫提供正確或必要的資訊，呼叫就會失敗。如需詳細資訊，請參閱 `error.errorMessage`、`error.errorDetails` 或 `error.GenerateErrorReport()`。
  * 裝置連線問題。行動電話會不斷失去/恢復連線，因此任何 API 呼叫都可能隨時隨機失敗，然後又立即恢復正常。進入隧道可能會讓您完全中斷連線。
  * PlayFab 伺服器問題。就像所有軟體一樣，可能會發生問題。如需更新資訊，請參閱我們的[版本資訊](/zh-TW/services/playfab/release-notes)。
* 網際網路並非 100% 可靠。有時訊息會損毀或無法送達 PlayFab 伺服器。
  * 您可以在[全域 API 方法錯誤碼](/zh-TW/services/playfab/api-references/global-api-method-error-codes)中找到全域 API 方法錯誤碼。
  * 如果您在偵錯問題時遇到困難，而錯誤資訊中的內容又不足夠，請造訪我們的[論壇](https://community.playfab.com/index.html)。

## 後續步驟

本快速入門示範了驗證使用者的簡化程序。如需使用者驗證的其他資訊，請參閱[登入基本概念和最佳做法](/zh-TW/services/playfab/identity/player-identity/login/login-basics-best-practices)。

祝您程式撰寫愉快！


## Related topics

- [PlayFab 支援的語言](/zh-TW/services/playfab/sdks/languages/index.md)
- [SDK Generator 快速入門](/zh-TW/services/playfab/sdks/sdkgenerator/quickstart.md)
- [快速入門](/zh-TW/services/playfab/economy-monetization/economy-v2/quickstart.md)
- [Party 快速入門](/zh-TW/services/playfab/multiplayer/networking/quickstart.md)
- [Android 快速入門](/zh-TW/services/playfab/sdks/c/quickstart-android.md)
