View a markdown version of this page

Usar GetBucketCors com o AWS SDK ou a CLI - Amazon Simple Storage Service

Usar GetBucketCors com o AWS SDK ou a CLI

Os exemplos de código a seguir mostram como usar GetBucketCors.

.NET
SDK para .NET
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

/// <summary> /// Retrieve the CORS configuration applied to the Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used /// to retrieve the CORS configuration.</param> /// <returns>The created CORS configuration object.</returns> private static async Task<CORSConfiguration> RetrieveCORSConfigurationAsync(AmazonS3Client client) { GetCORSConfigurationRequest request = new GetCORSConfigurationRequest() { BucketName = BucketName, }; var response = await client.GetCORSConfigurationAsync(request); var configuration = response.Configuration; PrintCORSRules(configuration); return configuration; }
  • Consulte detalhes da API em GetBucketCors na Referência da API AWS SDK para .NET.

CLI
AWS CLI

O seguinte comando recupera a configuração de compartilhamento de recursos de origem cruzada para o bucket amzn-s3-demo-bucket:

aws s3api get-bucket-cors --bucket amzn-s3-demo-bucket

Resultado:

{ "CORSRules": [ { "AllowedHeaders": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption" ], "AllowedMethods": [ "PUT", "POST", "DELETE" ], "MaxAgeSeconds": 3000, "AllowedOrigins": [ "http://www.example.com" ] }, { "AllowedHeaders": [ "Authorization" ], "MaxAgeSeconds": 3000, "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ] } ] }
  • Consulte detalhes da API em GetBucketCors na Referência de comandos da AWS CLI.

JavaScript
SDK para JavaScript (v3)
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

Obtenha a política de CORS para o bucket.

import { GetBucketCorsCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Log the Cross-Origin Resource Sharing (CORS) configuration information * set for the bucket. * @param {{ bucketName: string }} */ export const main = async ({ bucketName }) => { const client = new S3Client({}); const command = new GetBucketCorsCommand({ Bucket: bucketName, }); try { const { CORSRules } = await client.send(command); console.log(JSON.stringify(CORSRules)); CORSRules.forEach((cr, i) => { console.log( `\nCORSRule ${i + 1}`, `\n${"-".repeat(10)}`, `\nAllowedHeaders: ${cr.AllowedHeaders}`, `\nAllowedMethods: ${cr.AllowedMethods}`, `\nAllowedOrigins: ${cr.AllowedOrigins}`, `\nExposeHeaders: ${cr.ExposeHeaders}`, `\nMaxAgeSeconds: ${cr.MaxAgeSeconds}`, ); }); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while getting bucket CORS rules for ${bucketName}. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while getting bucket CORS rules for ${bucketName}. ${caught.name}: ${caught.message}`, ); } else { throw caught; } } };
Python
SDK para Python (Boto3).
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def get_cors(self): """ Get the CORS rules for the bucket. :return The CORS rules for the specified bucket. """ try: cors = self.bucket.Cors() logger.info( "Got CORS rules %s for bucket '%s'.", cors.cors_rules, self.bucket.name ) except ClientError: logger.exception(("Couldn't get CORS for bucket %s.", self.bucket.name)) raise else: return cors
  • Consulte detalhes da API em GetBucketCors na Referência da API AWS SDK para Python (Boto3).

Ruby
SDK para Ruby
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

require 'aws-sdk-s3' # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Gets the CORS configuration of a bucket. # # @return [Aws::S3::Type::GetBucketCorsOutput, nil] The current CORS configuration for the bucket. def cors @bucket_cors.data rescue Aws::Errors::ServiceError => e puts "Couldn't get CORS configuration for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" nil end end
  • Consulte detalhes da API em GetBucketCors na Referência da API AWS SDK para Ruby.

SAP ABAP
SDK para SAP ABAP
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

TRY. oo_result = lo_s3->getbucketcors( " oo_result is returned for testing purposes. " iv_bucket = iv_bucket_name ). MESSAGE 'Retrieved bucket CORS configuration.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
  • Para obter detalhes sobre a API, consulte GetBucketCors na Referência da API do SDK da AWS para SAP ABAP.

Para ver uma lista completa dos guias de desenvolvedor e exemplos de código do SDK da AWS, consulte Desenvolvimento com o Amazon S3 usando AWS SDKs. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.