Cross-Origin Resource Sharing (CORS) lets web applications running in a browser access resources from a different origin. OSS provides API operations to manage CORS rules on a bucket. The Node.js SDK methods described in this topic configure the bucket's CORS policy on the server side—they are not used inside the browser itself.
Prerequisites
Before you begin, ensure that you have:
Installed the
ali-ossnpm packageSet the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables with valid credentialsThe required permissions to manage CORS rules on the target bucket
CORS rule parameters
Each CORS rule accepts the following fields:
| Field | Description | Wildcard (*) | Example |
|---|---|---|---|
allowedOrigin | Origins allowed to make cross-origin requests. Use * to allow all origins. | Supported | http://example.com |
allowedMethod | HTTP methods allowed for cross-origin requests. Supported values: GET, PUT, DELETE, POST, HEAD. | - | GET |
allowedHeader | Request headers that cross-origin requests may include. Use * unless you have specific requirements. | Supported | * |
exposeHeader | Response headers that the browser can expose to JavaScript (for example, a XMLHttpRequest object). | Not supported | Content-Length |
maxAgeSeconds | How long, in seconds, the browser can cache the result of a preflight OPTIONS request. | - | 30 |
Set CORS rules
putBucketCORS(bucketName, rules) applies a list of CORS rules to a bucket. A bucket can have at most 10 CORS rules. If you configure a rule that is the same as an existing one, the existing rule is overwritten.
const OSS = require('ali-oss');
const client = new OSS({
// Replace with the region where your bucket is located, for example, oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
bucket: 'examplebucket',
});
const rules = [
{
allowedOrigin: 'http://example.com',
allowedMethod: 'GET',
allowedHeader: '*',
exposeHeader: 'Content-Length',
maxAgeSeconds: '30',
},
];
async function setCORSRules(bucketName, corsRules) {
try {
const result = await client.putBucketCORS(bucketName, corsRules);
console.log('CORS rules set successfully:', result);
} catch (e) {
console.error('Failed to set CORS rules:', e.name, e.message);
}
}
setCORSRules('examplebucket', rules);Get CORS rules
getBucketCORS(bucketName) retrieves the CORS rules configured for a bucket. The response includes result.res.status (HTTP status code) and result.rules (array of rule objects).
const OSS = require('ali-oss');
const client = new OSS({
region: 'oss-cn-hangzhou',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
bucket: 'examplebucket',
});
async function getCORSRules(bucketName) {
try {
const result = await client.getBucketCORS(bucketName);
console.log('HTTP status:', result.res.status);
console.log('CORS rules:', result.rules);
} catch (e) {
console.error('Failed to get CORS rules:', e.name, e.message);
}
}
getCORSRules('examplebucket');Delete CORS rules
deleteBucketCORS(bucketName) removes all CORS rules from a bucket. This operation cannot be undone.
const OSS = require('ali-oss');
const client = new OSS({
region: 'oss-cn-hangzhou',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
bucket: 'examplebucket',
});
async function deleteCORSRules(bucketName) {
try {
const result = await client.deleteBucketCORS(bucketName);
console.log('CORS rules deleted:', result);
} catch (e) {
console.error('Failed to delete CORS rules:', e.name, e.message);
}
}
deleteCORSRules('examplebucket');Usage notes
Rule limit: A bucket can have at most 10 CORS rules. If a new rule is identical to an existing one, the existing rule is overwritten.
exposeHeaderdoes not support wildcards: UnlikeallowedOriginandallowedHeader, theexposeHeaderfield does not accept*. List each header explicitly.Adding a rule without removing others: To add a rule while keeping existing ones, retrieve the current rules with
getBucketCORS, append the new rule to the array, then callputBucketCORSwith the full list.
What's next
For complete sample code, see the GitHub examples.
For the underlying API reference, see PutBucketCors, GetBucketCors, and DeleteBucketCors.