

AWS SDK for JavaScript v2가 지원 종료에 도달했습니다. [AWS SDK for JavaScript 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/ko_kr/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)

Amazon S3 버킷을 사용하는 CORS 구성 사용에 대한 자세한 내용은 *Amazon Simple Storage Service 사용 설명서*의 [CORS(Cross-Origin Resource Sharing)](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 구성이 있는 버킷을 지정합니다. 위와 같이 SDK를 구성해야 합니다. `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` 메서드에 필요한 CORS 구성의 값을 담을 JSON 객체를 생성합니다. `"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)에서 찾을 수 있습니다.