> ## 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)。有关创建 Title 和查找 TitleId 的信息，请参阅 [Game Manager 快速入门](/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 模板](/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 参考](/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 快速入门](/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 服务器问题。与所有软件一样，可能会出现问题。请参阅我们的 [发行说明](/services/playfab/release-notes) 获取更新。
* 互联网并非 100% 可靠。有时消息会损坏或无法到达 PlayFab 服务器。
  * 可以在 [全局 API 方法错误代码](/services/playfab/api-references/global-api-method-error-codes) 中查找全局 API 方法错误代码。
  * 如果你在调试问题时遇到困难，且错误信息中的内容不够充分，请访问我们的 [论坛](https://community.playfab.com/index.html)。

## 后续步骤

本快速入门展示了用户身份验证的简化流程。有关用户身份验证的更多信息，请参阅 [登录基础与最佳实践](/services/playfab/identity/player-identity/login/login-basics-best-practices)。

祝你编码愉快！


## Related topics

- [PlayFab 支持的语言](/zh-CN/services/playfab/sdks/languages/index.md)
- [快速入门](/zh-CN/services/playfab/economy-monetization/economy-v2/quickstart.md)
- [Android 快速入门](/zh-CN/services/playfab/sdks/c/quickstart-android.md)
- [iOS 快速入门](/zh-CN/services/playfab/sdks/c/quickstart-ios.md)
- [Linux 快速入门](/zh-CN/services/playfab/sdks/c/quickstart-linux.md)
