

 適用於 JavaScript 的 AWS SDK v2 已end-of-support。我們建議您遷移至 [適用於 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。如需如何遷移的其他詳細資訊和資訊，請參閱此[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

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

# 設定 Amazon S3 儲存貯體
<a name="s3-example-configuring-buckets"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 如何設定儲存貯體的跨來源資源共享 (CORS) 許可。

## 使用案例
<a name="s3-example-configuring-buckets-scenario"></a>

在此範例中使用了一系列的 Node.js 模組以列出您的 Amazon S3 儲存貯體，以及設定 CORS 和儲存貯體記錄。Node.js 模組使用適用於 JavaScript 的 SDK，使用以下 Amazon S3 用戶端類別的方法設定選取的 Amazon S3 儲存貯體：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketCors-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketCors-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketCors-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketCors-property)

如需搭配 Amazon S3 儲存貯體使用 CORS 組態的詳細資訊，請參閱《*Amazon Simple Storage Service 使用者指南*》中的[跨來源資源共享 (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html)。

## 先決條件任務
<a name="s3-example-configuring-buckets-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 安裝 Node.js。如需安裝 Node.js 的詳細資訊，請參閱 [Node.js 網站](https://nodejs.org)。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 [從共用登入資料檔案中在 Node.js 中載入登入資料](loading-node-credentials-shared.md)。

## 設定軟體開發套件
<a name="s3-example-configuring-buckets-configure-sdk"></a>

建立全域組態物件，然後為您的程式碼設定 區域，以設定適用於 JavaScript 的 SDK。在此範例中，區域會設為 `us-west-2`。

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 擷取儲存貯體 CORS 組態
<a name="s3-example-configuring-buckets-get-cors"></a>

以檔名 `s3_getcors.js` 建立一個 Node.js 模組。該模組將採用單一命令行引數來指定您需要的 CORS 組態之儲存貯體。請務必依前述的內容來設定軟體開發套件。建立一個 `AWS.S3` 服務物件。

您唯一需要傳遞的參數，就是在呼叫 `getBucketCors` 方法時所選取儲存貯體的名稱。如果儲存貯體目前具有 CORS 組態，Amazon S3 會將該組態傳回為傳遞給回呼函數的 `data` 參數`CORSRules`屬性。

如果所選的儲存貯體沒有 CORS 組態，則該資訊會在 `error` 參數中傳回至回呼函數。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Set the parameters for S3.getBucketCors
var bucketParams = { Bucket: process.argv[2] };

// call S3 to retrieve CORS configuration for selected bucket
s3.getBucketCors(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", JSON.stringify(data.CORSRules));
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node s3_getcors.js BUCKET_NAME
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getcors.js)找到這個範本程式碼。

## 設定儲存貯體 CORS 組態
<a name="s3-example-configuring-buckets-put-cors"></a>

以檔名 `s3_setcors.js` 建立一個 Node.js 模組。該模組採用多個命令行引數，第一個指定您想設定的 CORS 組態之儲存貯體。其他引數列舉您要為儲存貯體允許的 HTTP 方法 (POST, GET, PUT, PATCH, DELETE, POST)。依前述內容設定軟體開發套件。

 建立一個 `AWS.S3` 服務物件。接下來，視 `AWS.S3` 服務物件的 `putBucketCors` 方法需要，建立一個 JSON 物件以保存 CORS 組態的值。為 `AllowedHeaders` 值指定 `"Authorization"`，並為 `AllowedOrigins` 值指定 `"*"`。在初始時設 `AllowedMethods` 值為空陣列。

指定允許的方法為命令列參數至 Node.js 模組，新增符合其中一個參數的各種方法。新增產生的 CORS 組態至包含在 `CORSRules` 參數中的組態陣列。在 `Bucket` 參數中指定您要為 CORS 設定的儲存貯體。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create initial parameters JSON for putBucketCors
var thisConfig = {
  AllowedHeaders: ["Authorization"],
  AllowedMethods: [],
  AllowedOrigins: ["*"],
  ExposeHeaders: [],
  MaxAgeSeconds: 3000,
};

// Assemble the list of allowed methods based on command line parameters
var allowedMethods = [];
process.argv.forEach(function (val, index, array) {
  if (val.toUpperCase() === "POST") {
    allowedMethods.push("POST");
  }
  if (val.toUpperCase() === "GET") {
    allowedMethods.push("GET");
  }
  if (val.toUpperCase() === "PUT") {
    allowedMethods.push("PUT");
  }
  if (val.toUpperCase() === "PATCH") {
    allowedMethods.push("PATCH");
  }
  if (val.toUpperCase() === "DELETE") {
    allowedMethods.push("DELETE");
  }
  if (val.toUpperCase() === "HEAD") {
    allowedMethods.push("HEAD");
  }
});

// Copy the array of allowed methods into the config object
thisConfig.AllowedMethods = allowedMethods;
// Create array of configs then add the config object to it
var corsRules = new Array(thisConfig);

// Create CORS params
var corsParams = {
  Bucket: process.argv[2],
  CORSConfiguration: { CORSRules: corsRules },
};

// set the new CORS configuration on the selected bucket
s3.putBucketCors(corsParams, function (err, data) {
  if (err) {
    // display error message
    console.log("Error", err);
  } else {
    // update the displayed CORS config for the selected bucket
    console.log("Success", data);
  }
});
```

若要執行範例，請在命令列中輸入以下內容 (包含所示的一個或更多 HTTP 方法)。

```
node s3_setcors.js BUCKET_NAME get put
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_setcors.js)找到這個範本程式碼。