

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (V3) 的所有 API 操作。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 開始使用適用於 JavaScript 的 AWS SDK
<a name="getting-started"></a>

適用於 JavaScript 的 AWS SDK 可讓您存取瀏覽器或 Node.js 環境中的 Web 服務。本節提供入門練習，說明如何在每個 JavaScript 環境中使用適用於 JavaScript 的 AWS SDK。

**Topics**
+ [使用 進行 SDK 身分驗證 AWS](getting-your-credentials.md)
+ [Node.js 入門](getting-started-nodejs.md)
+ [在瀏覽器中開始使用](getting-started-browser.md)
+ [React Native 入門](getting-started-react-native.md)

# 使用 進行 SDK 身分驗證 AWS
<a name="getting-your-credentials"></a>

使用 進行開發 AWS 時，您必須建立程式碼向 進行身分驗證的方式 AWS 服務。您可以根據環境和您可用的存取權，以不同的方式設定 AWS 資源的程式設計 AWS 存取。

若要選擇您的身分驗證方法並為 SDK 設定，請參閱 *AWS SDKs和工具參考指南中的*[身分驗證和存取](https://docs.aws.amazon.com/sdkref/latest/guide/access.html)。

我們建議在本機開發 的新使用者，而不是由其雇主提供身分驗證方法來設定 AWS IAM Identity Center。此方法包括安裝 AWS CLI 以簡化組態，以及定期登入 AWS 存取入口網站。如果您選擇此方法，您的環境應該在您完成 *AWS SDKs和工具參考指南*中的 [IAM Identity Center 身分驗證](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html)程序後包含下列元素：
+ 在執行應用程式之前 AWS CLI，您用來啟動 AWS 存取入口網站工作階段的 。
+ 具有`[default]`設定檔的[共用 AWS`config`檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)，其中包含一組可從 SDK 參考的組態值。若要尋找此檔案的位置，請參閱 *AWS SDK 和工具參考指南*中的[共用檔案位置](https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html)。
+  共用`config`檔案會設定 [https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html)設定。這會設定軟體開發套件用於 AWS 請求 AWS 區域 的預設值。此區域用於未指定使用 區域的 SDK 服務請求。
+  開發套件使用描述檔的 [SSO 字符提供者組態](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#feature-sso-credentials-profile)，在傳送請求至 之前取得登入資料 AWS。`sso_role_name` 值是連接到 IAM Identity Center 許可集的 IAM 角色，允許存取應用程式中 AWS 服務 使用的 。

  下列範例`config`檔案顯示使用 SSO 字符提供者組態設定的預設設定檔。設定檔`sso_session`的設定是指具名[`sso-session`區段](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#section-session)。`sso-session` 區段包含啟動 AWS 存取入口網站工作階段的設定。

  ```
  [default]
  sso_session = my-sso
  sso_account_id = 111122223333
  sso_role_name = SampleRole
  region = us-east-1
  output = json
  
  [sso-session my-sso]
  sso_region = us-east-1
  sso_start_url = https://provided-domain.awsapps.com/start
  sso_registration_scopes = sso:account:access
  ```

適用於 JavaScript v3 的 AWS SDK 不需要將其他套件 （例如 `SSO`和 `SSOOIDC`) 新增至您的應用程式，即可使用 IAM Identity Center 身分驗證。

如需明確使用此登入資料提供者的詳細資訊，請參閱 [https://www.npmjs.com/package/@aws-sdk/credential-providers#fromsso](https://www.npmjs.com/package/@aws-sdk/credential-providers#fromsso) npm (Node.js 套件管理員） 網站上的 。

## 啟動 AWS 存取入口網站工作階段
<a name="accessportal"></a>

在執行存取的應用程式之前 AWS 服務，您需要 SDK 的作用中 AWS 存取入口網站工作階段，才能使用 IAM Identity Center 身分驗證來解析登入資料。視您設定的工作階段長度而定，您的存取最終會過期，且 SDK 將遇到身分驗證錯誤。若要登入 AWS 存取入口網站，請在 中執行下列命令 AWS CLI。

```
aws sso login
```

如果您遵循指引並設定預設設定檔，則不需要使用 `--profile`選項呼叫 命令。如果您的 SSO 權杖提供者組態使用已命名的設定檔，則命令為 `aws sso login --profile named-profile`。

若要選擇性地測試您是否已經有作用中的工作階段，請執行下列 AWS CLI 命令。

```
aws sts get-caller-identity
```

如果您的工作階段處於作用中狀態，對此命令的回應會報告共用`config`檔案中設定的 IAM Identity Center 帳戶和許可集。

**注意**  
如果您已有作用中的 AWS 存取入口網站工作階段並執行 `aws sso login`，則不需要提供登入資料。  
登入程序可能會提示您允許 AWS CLI 存取您的資料。由於 AWS CLI 建置在適用於 Python 的 SDK 之上，因此許可訊息可能包含`botocore`名稱的變化。

## 使用主控台登入憑證
<a name="use-con-login-creds"></a>

您可以使用現有的 AWS 管理主控台登入憑證，以程式設計方式存取 AWS 服務。在瀏覽器型身分驗證流程之後， AWS 會產生臨時登入資料，可用於本機開發工具，例如 CLI AWS 和適用於 JavaScript 的 AWS SDK。此功能可簡化設定和管理 AWS CLI 登入資料的程序。若要了解如何開始使用，請遵循[使用主控台登入資料登入以進行 AWS 本機開發](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html)的指示。

當您執行 **aws login**命令時，您可以從作用中主控台工作階段中選取 ，或透過瀏覽器型身分驗證流程登入，這會自動產生臨時登入資料。適用於 JavaScript 的 AWS SDK 會在過期前 5 分鐘自動重新整理登入資料，其中每組登入資料的有效時間最長為 12 小時。如需更多資訊，請參閱[https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromlogincredentials](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromlogincredentials)。

## 更多身分驗證資訊
<a name="credother"></a>

人類使用者具有*人類身分*，是應用程式的相關人員、管理員、開發人員、操作員和消費者。它們必須具有身分才能存取您的 AWS 環境和應用程式。屬於您組織成員的人類使用者 - 這表示您是開發人員 - 稱為*人力身分*。

存取時使用暫時登入資料 AWS。您可以為您的人類使用者使用身分提供者，透過擔任提供臨時登入資料的角色來提供 AWS 帳戶的聯合存取。對於集中式存取管理，我們建議您使用 AWS IAM Identity Center (IAM Identity Center) 來管理對帳戶和這些帳戶中許可的存取。如需更多替代方案，請參閱下列內容：
+ 如需了解有關最佳實務的資訊，請參閱 *IAM 使用者指南*中的 [IAM 安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。
+ 若要建立短期 AWS 登入資料，請參閱《*IAM 使用者指南*》中的[暫時安全登入](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)資料。
+ 若要了解適用於 JavaScript V3 憑證提供者的其他 AWS SDK，請參閱 SDK *AWS SDKs 和工具參考指南*中的[標準化憑證提供者](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)。

# Node.js 入門
<a name="getting-started-nodejs"></a>

本指南說明如何初始化 NPM 套件、將服務用戶端新增至套件，以及使用 JavaScript 開發套件呼叫服務動作。

## 案例
<a name="getting-started-nodejs-scenario"></a>

**使用執行下列動作的主檔案建立新的 NPM 套件：**
+ 建立 Amazon Simple Storage Service 儲存貯體
+ 將物件放入 Amazon S3 儲存貯體
+ 讀取 Amazon S3 儲存貯體中的物件
+ 確認使用者是否要刪除資源

## 先決條件
<a name="getting-started-nodejs-prerequisites"></a>

您必須先執行下列動作，才能執行範例：
+ 設定您的 SDK 身分驗證。如需詳細資訊，請參閱[使用 進行 SDK 身分驗證 AWS](getting-your-credentials.md)。
+ 使用 [Node.js](https://nodejs.org/en/download) 的 Active LTS 版本進行開發，安裝 Node.js. AWS recommends。

## 步驟 1：設定套件結構並安裝用戶端套件
<a name="getting-started-nodejs-setup-structure"></a>

若要設定套件結構並安裝用戶端套件：

1. 建立新的資料夾`nodegetstarted`以包含套件。

1. 從命令列導覽至新的資料夾。

1. 執行下列命令來建立預設`package.json`檔案：

   ```
   npm init -y
   ```

1. 執行下列命令來安裝 Amazon S3 用戶端套件：

   ```
   npm i @aws-sdk/client-s3
   ```

1. 將 `"type": "module"`新增至 `package.json` 檔案。這會通知 Node.js 使用現代 ESM 語法。最終看起來`package.json`應該類似以下內容：

   ```
   {
     "name": "example-javascriptv3-get-started-node",
     "version": "1.0.0",
     "description": "This guide shows you how to initialize an NPM package, add a service client to your package, and use the JavaScript SDK to call a service action.",
     "main": "index.js",
     "scripts": {
   "test": "vitest run **/*.unit.test.js"
     },
     "author": "Your Name",
     "license": "Apache-2.0",
     "dependencies": {
    "@aws-sdk/client-s3": "^3.420.0"
     },
     "type": "module"
   }
   ```

## 步驟 2：新增必要的匯入和 SDK 程式碼
<a name="getting-started-with-node-js-add-code"></a>

將下列程式碼新增至 `nodegetstarted` 資料夾中名為 `index.js` 的檔案。

```
// This is used for getting user input.
import { createInterface } from "node:readline/promises";

import {
  S3Client,
  PutObjectCommand,
  CreateBucketCommand,
  DeleteObjectCommand,
  DeleteBucketCommand,
  paginateListObjectsV2,
  GetObjectCommand,
} from "@aws-sdk/client-s3";

export async function main() {
  // A region and credentials can be declared explicitly. For example
  // `new S3Client({ region: 'us-east-1', credentials: {...} })` would
  //initialize the client with those settings. However, the SDK will
  // use your local configuration and credentials if those properties
  // are not defined here.
  const s3Client = new S3Client({});

  // Create an Amazon S3 bucket. The epoch timestamp is appended
  // to the name to make it unique.
  const bucketName = `test-bucket-${Date.now()}`;
  await s3Client.send(
    new CreateBucketCommand({
      Bucket: bucketName,
    }),
  );

  // Put an object into an Amazon S3 bucket.
  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
      Body: "Hello JavaScript SDK!",
    }),
  );

  // Read the object.
  const { Body } = await s3Client.send(
    new GetObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
    }),
  );

  console.log(await Body.transformToString());

  // Confirm resource deletion.
  const prompt = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  const result = await prompt.question("Empty and delete bucket? (y/n) ");
  prompt.close();

  if (result === "y") {
    // Create an async iterator over lists of objects in a bucket.
    const paginator = paginateListObjectsV2(
      { client: s3Client },
      { Bucket: bucketName },
    );
    for await (const page of paginator) {
      const objects = page.Contents;
      if (objects) {
        // For every object in each page, delete it.
        for (const object of objects) {
          await s3Client.send(
            new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }),
          );
        }
      }
    }

    // Once all the objects are gone, the bucket can be deleted.
    await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName }));
  }
}

// Call a function if this file was run directly. This allows the file
// to be runnable without running on import.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/index.js)範例程式碼。

## 步驟 3：執行範例
<a name="getting-started-with-node-js-run"></a>

**注意**  
請記得登入！如果您使用 IAM Identity Center 進行身分驗證，請記得使用 AWS CLI `aws sso login`命令登入。

1. 執行 `node index.js`。

1. 選擇是否清空並刪除儲存貯體。

1. 如果您未刪除儲存貯體，請務必手動清空並稍後刪除。

# 在瀏覽器中開始使用
<a name="getting-started-browser"></a>

本節會逐步解說範例，示範如何在瀏覽器中執行適用於 JavaScript 的 AWS SDK 第 3 版 (V3)。

**注意**  
在瀏覽器中執行 V3 與第 2 版 (V2) 略有不同。如需詳細資訊，請參閱[在 V3 中使用瀏覽器](welcome.md#v3_browsers)。

如需使用適用於 JavaScript 的 AWS SDK (V3) 的其他範例，請參閱 [適用於 JavaScript (v3) 的 SDK 程式碼範例](javascript_code_examples.md)。

**此 Web 應用程式範例顯示：**
+ 如何使用 Amazon Cognito 存取 AWS 服務以進行身分驗證。
+ 如何使用 a(IAM) 角色讀取 Amazon Simple Storage Service AWS Identity and Access Management (Amazon S3) 儲存貯體中的物件清單。

**注意**  
此範例不會使用 AWS IAM Identity Center 進行身分驗證。

## 使用案例
<a name="getting-started-browser-scenario"></a>

Amazon S3 是一項物件儲存服務，提供領先業界的可擴展性、資料可用性、安全性和效能。您可以使用 Amazon S3 將資料作為物件存放在稱為儲存貯體的容器中。如需 Amazon S3 的詳細資訊，請參閱《[Amazon S3 使用者指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)》。

此範例說明如何設定和執行 Web 應用程式，以擔任要從 Amazon S3 儲存貯體讀取的 IAM 角色。此範例使用 React 前端程式庫和 Vite 前端工具來提供 JavaScript 開發環境。Web 應用程式使用 Amazon Cognito 身分集區來提供存取 AWS 服務所需的登入資料。隨附的程式碼範例示範在 Web 應用程式中載入和使用適用於 JavaScript 的 AWS SDK 的基本模式。

## 步驟 1：建立 Amazon Cognito 身分集區和 IAM 角色
<a name="getting-started-browser-create-identity-pool"></a>

在本練習中，您會建立並使用 Amazon Cognito 身分集區，為 Amazon S3 服務提供未經驗證的 Web 應用程式存取權。建立身分集區也會建立 AWS Identity and Access Management (IAM) 角色，以支援未經驗證的訪客使用者。在此範例中，我們只會使用未經驗證的使用者角色來保持任務重點。您之後可以整合對身分提供者和已驗證使用者的支援。如需新增 Amazon Cognito 身分集區的詳細資訊，請參閱《*Amazon Cognito 開發人員指南*》中的[教學課程：建立身分集](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-identity-pool.html)區。

**建立 Amazon Cognito 身分集區和相關聯的 IAM 角色**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/) 的 Amazon Cognito 主控台。

1. 在左側導覽窗格中，選擇**身分集區**。

1. 選擇 **建立身分池**。

1. 在**設定身分集區信任**中，選擇**訪客存取權**以進行使用者身分驗證。

1. 在**設定許可**中，選擇**建立新的 IAM 角色**，然後在 **IAM 角色**名稱中輸入名稱 （例如 *getStartedRole*)。

1. 在**設定屬性**中，在**身分集**區名稱中輸入名稱 （例如 *getStartedPool*)。

1. 在 **檢閱和建立** 中，確認您為新身分池所做的選擇。選取 **編輯** 以返回精靈並變更任何設定。當您完成時，請選取 **建立身分池**。

1. 請注意**身分集區 ID** 和新建立的 Amazon Cognito 身分集區的**區域**。您需要這些值來取代 中的 *IDENTITY\$1POOL\$1ID* 和 *REGION*[步驟 4：設定瀏覽器程式碼](#getting-started-browser-create-html)。

建立 Amazon Cognito 身分集區後，您就可以新增 Web 應用程式所需的 Amazon S3 許可。

## 步驟 2：將政策新增至建立的 IAM 角色
<a name="getting-started-browser-iam-role"></a>

若要在 Web 應用程式中啟用對 Amazon S3 儲存貯體的存取，請使用為 Amazon Cognito 身分集區 （例如 getStartedPool) 建立的未驗證 IAM 角色 （例如 *getStartedRole*)。 *getStartedPool* 這需要您將 IAM 政策連接至角色。如需修改 IAM 角色的詳細資訊，請參閱《*IAM 使用者指南*》中的[修改角色許可政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_permissions-policy)。

**將 Amazon S3 政策新增至與未驗證使用者相關聯的 IAM 角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在左側導覽窗格中，選擇 **Roles** (角色)。

1. 選擇您要修改的角色名稱 （例如 *getStartedRole*)，然後選擇**許可**索引標籤。

1. 選擇**新增許可**，然後選擇**連接政策**。

1. 在**新增此角色的許可**頁面中，尋找並選取 **AmazonS3ReadOnlyAccess** 的核取方塊。
**注意**  
您可以使用此程序來啟用對任何 AWS 服務的存取。

1. 選擇**新增許可**。

建立 Amazon Cognito 身分集區並將 Amazon S3 的許可新增至未經驗證使用者的 IAM 角色之後，您就可以新增和設定 Amazon S3 儲存貯體。

## 步驟 3：新增 Amazon S3 儲存貯體和物件
<a name="getting-started-browser-create-s3-bucket"></a>

在此步驟中，您將為範例新增 Amazon S3 儲存貯體和物件。您也將啟用儲存貯體的跨來源資源共用 (CORS)。如需建立 Amazon S3 儲存貯體和物件的詳細資訊，請參閱《[Amazon S3 使用者指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html)*》中的 Amazon S3 *入門。

**使用 CORS 新增 Amazon S3 儲存貯體和物件**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)：// 開啟 Amazon S3 主控台。

1. 在左側導覽窗格中，選擇**儲存貯體**，然後選擇**建立儲存貯體**。

1. 輸入符合儲存貯體[命名規則的儲存貯體名稱 ](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html)（例如 *getstartedbucket*)，然後選擇**建立儲存貯體**。

1. 選擇您建立的儲存貯體，然後選擇**物件**索引標籤。然後選擇 **Upload (上傳)**。

1. 在**檔案和資料夾**下，選擇**新增檔案**。

1. 選擇要上傳的檔案，然後選擇 **Open (開啟)**。然後選擇**上傳**以完成將物件上傳至儲存貯體。

1. 接著，選擇儲存貯體的**許可**索引標籤，然後在**跨來源資源共用 (CORS)** 區段中選擇**編輯**。輸入下列 JSON：

   ```
   [
     {
       "AllowedHeaders": [
         "*"
       ],
       "AllowedMethods": [
         "GET"
       ],
       "AllowedOrigins": [
         "*"
       ],
       "ExposeHeaders": []
     }
   ]
   ```

1. 選擇**儲存變更**。

新增 Amazon S3 儲存貯體並新增物件之後，您就可以設定瀏覽器程式碼。

## 步驟 4：設定瀏覽器程式碼
<a name="getting-started-browser-create-html"></a>

範例應用程式由單頁 React 應用程式組成。您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/web/s3/list-objects)此範例的檔案。

**設定範例應用程式**

1. 安裝 [Node.js](https://nodejs.org/en/download)。

1. 從命令列複製[AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/)：

   ```
   git clone --depth 1 https://github.com/awsdocs/aws-doc-sdk-examples.git
   ```

1. 導覽至範例應用程式：

   ```
   cd aws-doc-sdk-examples/javascriptv3/example_code/web/s3/list-objects/
   ```

1. 執行下列命令來安裝必要的套件：

   ```
   npm install
   ```

1. 接著，在文字編輯器`src/App.tsx`中開啟 ，並完成下列操作：
   + 以您在 中記下的 Amazon Cognito 身分集區 ID 取代 *YOUR\$1IDENTITY\$1POOL\$1ID*[步驟 1：建立 Amazon Cognito 身分集區和 IAM 角色](#getting-started-browser-create-identity-pool)。
   + 將區域 的值取代為您的 Amazon S3 儲存貯體和 Amazon Cognito 身分集區指派的區域。請注意，這兩個服務的區域必須相同 （例如 *us-east-2*)。
   + 將 *bucket-name* 取代為您在 中建立的儲存貯體名稱[步驟 3：新增 Amazon S3 儲存貯體和物件](#getting-started-browser-create-s3-bucket)。

取代文字之後，請儲存`App.tsx`檔案。您現在已準備好執行 Web 應用程式。

## 步驟 5：執行範例
<a name="getting-started-browser-run-sample"></a>

**執行範例應用程式**

1. 從命令列導覽至範例應用程式：

   ```
   cd aws-doc-sdk-examples/javascriptv3/example_code/web/s3/list-objects/
   ```

1. 從命令列執行下列命令：

   ```
   npm run dev
   ```

   Vite 開發環境將執行並顯示下列訊息：

   ```
   VITE v4.3.9  ready in 280 ms
   
   ➜  Local:   http://localhost:5173/
   ➜  Network: use --host to expose
   ➜  press h to show help
   ```

1. 在網頁瀏覽器中，導覽至上面顯示的 URL （例如 http://localhost:5173)。範例應用程式會顯示 Amazon S3 儲存貯體中的物件檔案名稱清單。

## 清除
<a name="getting-started-browser-cleanup"></a>

若要清除您在本教學課程中建立的資源，請執行下列動作：
+ [在 Amazon S3 主控台](https://console.aws.amazon.com/s3/)中，刪除任何物件和建立的任何儲存貯體 （例如 *getstartedbucket*)。
+ [在 IAM 主控台](https://console.aws.amazon.com/iam/home#/roles)中，刪除角色名稱 （例如 *getStartedRole*)。
+ [在 Amazon Cognito 主控台](https://console.aws.amazon.com/cognito/home#/identity)中，刪除身分集區名稱 （例如 *getStartedPool*)。

# React Native 入門
<a name="getting-started-react-native"></a>

本教學課程說明如何使用 React Native [CLI 建立 React Native](https://reactnative.dev/docs/environment-setup) 應用程式。

![\[JavaScript code example that applies to React Native.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/browsericon.png)

**本教學課程顯示：**
+ 如何安裝和包含專案使用的適用於 JavaScript 的 AWS SDK 第 3 版 (V3) 模組。
+ 如何撰寫連線至 Amazon Simple Storage Service (Amazon S3) 的程式碼，以建立和刪除 Amazon S3 儲存貯體。

## 使用案例
<a name="getting-started-react-scenario"></a>

Amazon S3 是一種雲端服務，可讓您隨時從 Web 上的任何位置存放和擷取任意數量的資料。React Native 是一種開發架構，可讓您建立行動應用程式。本教學課程說明如何建立連線至 Amazon S3 的 React Native 應用程式，以建立和刪除 Amazon S3 儲存貯體。

應用程式使用下列適用於 JavaScript APIs AWS SDK：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity/) 建構函數
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/) 建構函數

## 先決條件任務
<a name="getting-started-react-setup"></a>

**注意**  
如果您已透過其他教學課程或現有組態完成下列任何步驟，請略過這些步驟。

本節提供完成此教學課程所需的最小設定。您不應將它視為完整的設定。針對該資訊，請參閱 [設定適用於 JavaScript 的 SDK](setting-up.md)。
+ 安裝下列工具：
  + [npm](https://docs.npmjs.com/getting-started/)
  + [Node.js](https://nodejs.org/en/download/)
  + [https://developer.apple.com/xcode/](https://developer.apple.com/xcode/) 如果您在 iOS 上測試
  + 如果您在 [Android 上測試 Android Studio](https://developer.android.com/studio/) 
+ 設定您的 [React Native 開發環境](https://reactnative.dev/docs/environment-setup)
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝適用於 JavaScript 和第三方模組的必要 AWS SDK。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/README.md) 上的指示。
+ 使用 AWS 服務進行開發 AWS 時，您必須建立程式碼與 進行身分驗證的方式。如需詳細資訊，請參閱[使用 進行 SDK 身分驗證 AWS](getting-your-credentials.md)。
**注意**  
此範例的 IAM 角色應設定為使用 **AmazonS3FullAccess** 許可。

## 步驟 1：建立 Amazon Cognito 身分集區
<a name="getting-started-react-create-identity-pool"></a>

在本練習中，您會建立並使用 Amazon Cognito Identity 集區，為 Amazon S3 服務提供未經驗證的應用程式存取權。建立身分集區也會建立兩個 AWS Identity and Access Management (IAM) 角色，一個用於支援身分提供者驗證的使用者，另一個用於支援未經驗證的訪客使用者。

在本範例中，我們只會使用未經驗證的使用者角色，以專注進行任務重點。您之後可以整合對身分提供者和已驗證使用者的支援。

**建立 Amazon Cognito 身分集區**

1. 登入 AWS 管理主控台 ，並在 Amazon Web Services 主控台開啟 Amazon Cognito [主控台](https://console.aws.amazon.com/cognito/)。

1. 在主控台開啟頁面上選擇**身分集區**。

1. 在下一頁中，選擇 **Create new identity pool (建立新的身分集區)**。
**注意**  
如果沒有其他身分集區，Amazon Cognito 主控台會略過此頁面並改為開啟下一頁。

1. 在**設定身分集區信任**中，選擇**訪客存取權**以進行使用者身分驗證。

1. 在**設定許可**中，選擇**建立新的 IAM 角色**，然後在 **IAM 角色**名稱中輸入名稱 （例如 *getStartedReactRole*)。

1. 在**設定屬性**中，在**身分集**區名稱中輸入名稱 （例如 *getStartedReactPool*)。

1. 在 **檢閱和建立** 中，確認您為新身分池所做的選擇。選取 **編輯** 以返回精靈並變更任何設定。當您完成時，請選取 **建立身分池**。

1. 請記下此新建立之身分集區的身分集區 ID 和 區域。您需要這些值來取代瀏覽器指令碼中的 *region* 和 *identityPoolId*。

建立 Amazon Cognito 身分集區後，您就可以新增 React Native 應用程式所需的 Amazon S3 許可。

## 步驟 2：將政策新增至已建立的 IAM 角色
<a name="getting-started-react-iam-role"></a>

若要啟用瀏覽器指令碼存取 Amazon S3 以建立和刪除 Amazon S3 儲存貯體，請使用為 Amazon Cognito 身分集區建立的未驗證 IAM 角色。這需要您將 IAM 政策新增至角色。如需 IAM 角色的詳細資訊，請參閱《*IAM 使用者指南*》中的[建立角色以將許可委派給 AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)。

**將 Amazon S3 政策新增至與未驗證使用者相關聯的 IAM 角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在左側導覽窗格中，選擇 **Roles** (角色)。

1. 選擇您要修改的角色名稱 （例如 *getStartedRole*)，然後選擇**許可**索引標籤。

1. 選擇**新增許可**，然後選擇**連接政策**。

1. 在**新增此角色的許可**頁面中，尋找並選取 **AmazonS3ReadOnlyAccess** 的核取方塊。
**注意**  
您可以使用此程序來啟用對任何 AWS 服務的存取。

1. 選擇**新增許可**。

建立 Amazon Cognito 身分集區並將 Amazon S3 的許可新增至未經驗證使用者的 IAM 角色之後，您就可以建置應用程式。

## 步驟 3：使用 create-react-native-app 建立應用程式
<a name="react-prerequisites"></a>

執行下列命令來建立 React Native 應用程式。

```
npx react-native init ReactNativeApp --npm
```

## 步驟 4：安裝 Amazon S3 套件和其他相依性
<a name="getting-started-react-install-dependencies"></a>

在專案的 目錄中，執行下列命令來安裝 Amazon S3 套件。

```
npm install @aws-sdk/client-s3
```

此命令會在您的專案中安裝 Amazon S3 套件，並更新`package.json`以將 Amazon S3 列為專案相依性。您可以在 [https://www.npmjs.com/](https://www.npmjs.com/)npm 網站上搜尋 "@aws-sdk"，以找到此套件的相關資訊。

系統會在專案的 `node_modules` 子目錄中安裝這些套件及其相關聯的程式碼。

如需安裝 Node.js 套件的詳細資訊，請參閱 npm (Node.js 套件管理員） 網站上的[在本機下載和安裝](https://docs.npmjs.com/downloading-and-installing-packages-locally)套件和建立 Node.js 模組。 [https://docs.npmjs.com/creating-node-js-modules](https://docs.npmjs.com/creating-node-js-modules) [https://www.npmjs.com/](https://www.npmjs.com/)如需有關下載和安裝適用於 JavaScript 的 AWS SDK 的資訊，請參閱 [安裝適用於 JavaScript 的軟體開發套件](setting-up.md#installing-jssdk)。

安裝身分驗證所需的其他相依性。

```
npm install @aws-sdk/client-cognito-identity @aws-sdk/credential-provider-cognito-identity
```

## 步驟 5：撰寫 React Native 程式碼
<a name="getting-started-react-write-native-code"></a>

將下列程式碼新增至 `App.tsx`。將 *identityPoolId* 和*區域*取代為身分集區 ID 和建立 Amazon S3 儲存貯體的區域。

```
import React, { useCallback, useState } from "react";
import { Button, StyleSheet, Text, TextInput, View } from "react-native";
import "react-native-get-random-values";
import "react-native-url-polyfill/auto";

import {
  S3Client,
  CreateBucketCommand,
  DeleteBucketCommand,
} from "@aws-sdk/client-s3";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const client = new S3Client({
  // The AWS Region where the Amazon Simple Storage Service (Amazon S3) bucket will be created. Replace this with your Region.
  region: "us-east-1",
  credentials: fromCognitoIdentityPool({
    // Replace the value of 'identityPoolId' with the ID of an Amazon Cognito identity pool in your Amazon Cognito Region.
    identityPoolId: "us-east-1:edbe2c04-7f5d-469b-85e5-98096bd75492",
    // Replace the value of 'region' with your Amazon Cognito Region.
    clientConfig: { region: "us-east-1" },
  }),
});

enum MessageType {
  SUCCESS = 0,
  FAILURE = 1,
  EMPTY = 2,
}

const App = () => {
  const [bucketName, setBucketName] = useState("");
  const [msg, setMsg] = useState<{ message: string; type: MessageType }>({
    message: "",
    type: MessageType.EMPTY,
  });

  const createBucket = useCallback(async () => {
    setMsg({ message: "", type: MessageType.EMPTY });

    try {
      await client.send(new CreateBucketCommand({ Bucket: bucketName }));
      setMsg({
        message: `Bucket "${bucketName}" created.`,
        type: MessageType.SUCCESS,
      });
    } catch (e) {
      console.error(e);
      setMsg({
        message: e instanceof Error ? e.message : "Unknown error",
        type: MessageType.FAILURE,
      });
    }
  }, [bucketName]);

  const deleteBucket = useCallback(async () => {
    setMsg({ message: "", type: MessageType.EMPTY });

    try {
      await client.send(new DeleteBucketCommand({ Bucket: bucketName }));
      setMsg({
        message: `Bucket "${bucketName}" deleted.`,
        type: MessageType.SUCCESS,
      });
    } catch (e) {
      setMsg({
        message: e instanceof Error ? e.message : "Unknown error",
        type: MessageType.FAILURE,
      });
    }
  }, [bucketName]);

  return (
    <View style={styles.container}>
      {msg.type !== MessageType.EMPTY && (
        <Text
          style={
            msg.type === MessageType.SUCCESS
              ? styles.successText
              : styles.failureText
          }
        >
          {msg.message}
        </Text>
      )}
      <View>
        <TextInput
          onChangeText={(text) => setBucketName(text)}
          autoCapitalize={"none"}
          value={bucketName}
          placeholder={"Enter Bucket Name"}
        />
        <Button color="#68a0cf" title="Create Bucket" onPress={createBucket} />
        <Button color="#68a0cf" title="Delete Bucket" onPress={deleteBucket} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  successText: {
    color: "green",
  },
  failureText: {
    color: "red",
  },
});

export default App;
```

程式碼會先匯入所需的 React、React Native 和 AWS SDK 相依性。

在函數應用程式中：
+ 系統會建立 S3Client 物件，並使用先前建立的 Amazon Cognito 身分集區指定登入資料。
+ 方法 `createBucket`和 會分別`deleteBucket`建立和刪除指定的儲存貯體。
+ React Native View 會顯示文字輸入欄位，讓使用者指定 Amazon S3 儲存貯體名稱，以及建立和刪除指定 Amazon S3 儲存貯體的按鈕。

您可以在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/reactnative/ReactNativeApp/App.tsx)完整的 JavaScript 頁面。

## 步驟 6：執行範例
<a name="getting-started-react-native-run-sample"></a>

**注意**  
請記得登入！如果您使用 IAM Identity Center 進行身分驗證，請記得使用 AWS CLI `aws sso login`命令登入。

若要執行範例，請使用 npm `web`執行 `ios`、 或 `android`命令。

以下是在 macOS 上執行`ios`命令的範例輸出。

```
$ npm run ios

> ReactNativeApp@0.0.1 ios /Users/trivikr/workspace/ReactNativeApp
> react-native run-ios

info Found Xcode workspace "ReactNativeApp.xcworkspace"
info Launching iPhone 11 (iOS 14.2)
info Building (using "xcodebuild -workspace ReactNativeApp.xcworkspace -configuration Debug -scheme ReactNativeApp -destination id=706C1A97-FA38-407D-AD77-CB4FCA9134E9")
success Successfully built the app
info Installing "/Users/trivikr/Library/Developer/Xcode/DerivedData/ReactNativeApp-cfhmsyhptwflqqejyspdqgjestra/Build/Products/Debug-iphonesimulator/ReactNativeApp.app"
info Launching "org.reactjs.native.example.ReactNativeApp"

success Successfully launched the app on the simulator
```

以下是在 macOS 上執行`android`命令的範例輸出。

```
$ npm run android

> ReactNativeApp@0.0.1 android
> react-native run-android

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 970 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug
02:18:38 V/ddms: execute: running am get-config
02:18:38 V/ddms: execute 'am get-config' on 'emulator-5554' : EOF hit. Read: -1
02:18:38 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Pixel_3a_API_30_x86(AVD) - 11' for app:debug
02:18:38 D/app-debug.apk: Uploading app-debug.apk onto device 'emulator-5554'
02:18:38 D/Device: Uploading file onto device 'emulator-5554'
02:18:38 D/ddms: Reading file permission of /Users/trivikr/workspace/ReactNativeApp/android/app/build/outputs/apk/debug/app-debug.apk as: rw-r--r--
02:18:40 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
02:18:41 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
02:18:41 V/ddms: execute: returning
02:18:41 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
02:18:41 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
02:18:41 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 6s
27 actionable tasks: 2 executed, 25 up-to-date
info Connecting to the development server...
8081
info Starting the app on "emulator-5554"...
Starting: Intent { cmp=com.reactnativeapp/.MainActivity }
```

輸入您要建立或刪除的儲存貯體名稱，然後按一下**建立儲存貯體****或刪除儲存貯體**。相應的命令將傳送至 Amazon S3，並顯示成功或錯誤訊息。

![\[Bucket creation success message with options to create or delete a bucket.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/react-app-running.png)


## 可能的增強功能
<a name="getting-started-react-native-variations"></a>

以下是此應用程式的變化，您可以用來進一步探索在 React Native 應用程式中使用適用於 JavaScript 的 AWS SDK。
+ 新增按鈕以列出 Amazon S3 儲存貯體，並在列出的每個儲存貯體旁提供刪除按鈕。
+ 新增按鈕，將文字物件放入儲存貯體。
+ 整合 Facebook 或 Amazon 等外部身分提供者，以搭配已驗證的 IAM 角色使用。