Todos os produtos
Search
Central de documentação

Object Storage Service:Cross-origin resource sharing (Node.js SDK)

Última atualização: Jul 03, 2026

O compartilhamento de recursos de origem cruzada (CORS) permite que aplicações web acessem recursos de um domínio diferente. O OSS fornece operações de API para CORS, permitindo controlar as permissões de acesso entre domínios.

Defina regras de CORS

O código a seguir define as regras de CORS para um bucket:

const OSS = require('ali-oss');

const client = new OSS({
  // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: 'yourBucket'
});

const rules = [{
        // Specify the allowed origins for cross-origin requests. The wildcard character asterisk (*) is supported, which allows all source domains.
        allowedOrigin: 'http://example.com',
        // Specify the allowed methods for cross-origin requests. Supported methods include GET, PUT, DELETE, POST, and HEAD.
        allowedMethod: 'GET',
        // Specify the allowed response headers for cross-origin requests. Set this to the wildcard character asterisk (*) unless you have specific requirements.
        allowedHeader: '*',
        // Specify the response headers that users can access from applications, such as a JavaScript XMLHttpRequest object. The wildcard character asterisk (*) is not allowed.
        exposeHeader: 'Content-Length',
        // Specify the cache duration, in seconds, for the results of preflight (OPTIONS) requests for a specific resource.
        maxAgeSeconds: '30'
  },
];
// Set a maximum of 10 CORS rules. If you configure a rule that is the same as an existing one, the existing rule is overwritten.
client.putBucketCORS("yourBucket", rules).then((r) => {
  console.log(r);
});           

Obter regras de CORS

O código a seguir recupera as regras de CORS de um bucket:

const OSS = require("ali-oss");
const assert = require("assert");

const client = new OSS({
  // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: "yourBucket",
});

// Specify the bucket name.
client.getBucketCORS("yourBucket").then((r) => {
  assert.equal(r.res.status, 200);
  assert.deepEqual(r.rules, [
    {
      allowedOrigin: "http://example.com",
      allowedMethod: "GET",
      allowedHeader: "*",
      exposeHeader: "Content-Length",
      maxAgeSeconds: "30",
    },
  ]);
});

Exclua regras de CORS

O código a seguir exclui todas as regras de CORS de um bucket:

const OSS = require('ali-oss');

const client = new OSS({
  // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: "yourBucket",
});

// Specify the bucket name.
client.deleteBucketCORS('yourBucket').then((res) => {
  console.log(res);
}).catch(e => {
  console.log(e)
})

Referências

  • Para obter o código de exemplo completo sobre compartilhamento de recursos de origem cruzada, consulte os exemplos no GitHub.

  • Para obter mais informações sobre a operação de API usada para definir regras de CORS, consulte PutBucketCors.

  • Para obter mais informações sobre a operação de API usada para recuperar regras de CORS, consulte GetBucketCors.

  • Para obter mais informações sobre a operação de API usada para excluir regras de CORS, consulte DeleteBucketCors.