

适用于 JavaScript 的 AWS SDK v2 已终止支持。建议您迁移到 [适用于 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_cn/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 模块使用 SDK for JavaScript，通过 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)

有关将 CORS 配置与 Amazon S3 桶配合使用的更多信息，请参阅《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)。

## 配置 SDK
<a name="s3-example-configuring-buckets-configure-sdk"></a>

通过创建全局配置对象然后为代码设置区域，来配置 SDK for JavaScript。在此示例中，区域设置为 `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）。按前面所示配置 SDK。

 创建 `AWS.S3` 服务对象。接下来，根据 `putBucketCors` 服务对象的 `AWS.S3` 方法的要求，创建一个 JSON 对象来保存 CORS 配置的值。为 `"Authorization"` 值指定 `AllowedHeaders`，为 `"*"` 值指定 `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)找到。