Initialization
Determine Endpoint
Before configuring the Endpoint for SDK usage, please refer to the developer guide section on [BOS Access Domain Name](BOS/Developer Guide/Basic concepts.md#Endpoint) to understand Endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md).
Refer to the following link for region and endpoint
https://cloud.baidu.com/doc/BOS/s/akrqd2wcx
Common examples are as follows:
| Region | Access endpoint | Supported protocols |
|---|---|---|
| bj | bj.bcebos.com | HTTP,HTTPS |
| bd | bd.bcebos.com | HTTP,HTTPS |
| su | su.bcebos.com | HTTP,HTTPS |
| gz | gz.bcebos.com | HTTP,HTTPS |
| cd | cd.bcebos.com | HTTP,HTTPS |
| hkg | hkg.bcebos.com | HTTP,HTTPS |
| fwh | fwh.bcebos.com | HTTP,HTTPS |
| fsh | fsh.bcebos.com | HTTP,HTTPS |
Quick start for Node.js
- Begin by initializing a BOSClient.
A BosClient is used to interface with the BOS service, and all BOS operations in the BOS JavaScript SDK are performed via the BosClient.
Note: For enhanced security, it is recommended to initialize a BosClient using STS authentication.
Sample code (with STS authentication):
1var sdk = require('@baiducloud/sdk');
2var BosClient = sdk.BosClient;
3var config = {
4 credentials: {
5 ak: '{accessKeyId}', // Temporary AK issued by the STS server
6 sk: '{secretAccessKey}' // Temporary SK issued by the STS server
7 },
8 sessionToken: '{sessionToken}', // sessionToken issued by the STS server
9 endpoint: 'https://bj.bcebos.com' //Need to be modified according to the region where the bucket belongs
10};
Sample code (without STS authentication):
1var sdk = require('@baiducloud/sdk');
2var BosClient = sdk.BosClient;
3var config = {
4 credentials: {
5 ak: 'ak', //Your AK
6 sk: 'sk' //Your SK
7 },
8 endpoint: 'https://bj.bcebos.com' //Need to be modified according to the region where the bucket belongs
9};
- Create a bucket.
1A bucket is a namespace in BOS that serves as a container for data and can hold multiple data entities (objects). You must create a bucket before uploading data.
2
3Example code:
4```js
5let newBucketName = <BucketName>; //reate a new bucket and specify the bucket name
6client.createBucket(newBucketName)
7 .then(function() {
8 // Creation completed, add your own code;
9 })
10 .catch(function(error) {
11 // Creation failed, add your own code to handle the exception
12 });
13```
- Upload an object.
1An object is the basic data unit in BOS. You can think of an object as a file. For simple object uploads, BOS provides four methods: file upload, data stream upload, binary string upload, and string upload.
2
3Example code:
4
5```js
6function done(response) {
7 // Upload completed
8}
9function fail(fail) {
10 // Upload failed
11}
12 // Upload in string form
13client.putObjectFromString(bucket, object, 'hello world')
14 .then(done)
15 .catch(fail);
16 // Upload in buffer form
17var buffer = new Buffer('hello world'); client.putObject(bucket, object, buffer)
18 .then(done)
19 .catch(fail);
20 // Upload in file form, only supported in Node.js environment
21client.putObjectFromFile(bucket, object, <path-to-file>)
22 .then(done)
23 .catch(fail);
24 // Upload in blob object form, only supported in browser environment
25 client.putObjectFromBlob(bucket, object, <blob object>)
26 .then(done)
27 .catch(fail);
28```
- View the object in the bucket.
1You can refer to the following code to view the list of objects in the bucket:
2```js
3client.listObjects(<bucketName>)
4 .then(function (response) {
5 var contents = response.body.contents;
6 for (var i = 0, l = contents.length; i < l; i++) {
7 console.log(contents[i].key);
8 }
9 })
10 .catch(function (error) {
11 // Query failed
12 });
13```
Create a BosClient
The BosClient is the JavaScript client for BOS services, providing developers with multiple methods to interact with BOS functionality. Before sending requests via the SDK, you must first initialize a BosClient instance and configure the necessary settings.
- Browser side:
let BosClient = baidubce.sdk.BosClient - Node.js side:
import {BosClient} from '@baiducloud/sdk'
Accessing BOS via STS
Note: Since mobile environments are inherently untrusted, there is a significant security risk in storing AccessKeyId and SecretAccessKey directly on the device for request signing. It is recommended to use the STS authentication mode to securely access BOS.
BOS enables temporary third-party access authorization through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu AI Cloud. For details, please refer to [Baidu AI Cloud STS Usage Guide](BOS/API Reference/Access control.md). Through STS, you can issue access credentials with customized validity periods and permissions to third-party users. Third-party users can use these credentials to directly call Baidu AI Cloud APIs or SDKs to access cloud resources.
To access BOS via STS, users first apply for a set of AK, SK, and token through the sts-client, and then configure this set of parameters into the BosClient. Users can refer to the following code to create a new BosClient:
- Node.js side:
1const {BosClient} = require('@baiducloud/sdk');
2var bosConfig = {
3 credentials: {
4 ak: '{accessKeyId}', // Temporary AK issued by the STS server
5 sk: '{secretAccessKey}' // Temporary SK issued by the STS server
6 },
7 sessionToken: '{sessionToken}', // sessionToken issued by the STS server
8 endpoint: 'http://bj.bcebos.com' //Need to be modified according to the region where the bucket belongs
9};
10var client = new BosClient(bosConfig);
- Browser side:
1var bosConfig = {
2 credentials: {
3 ak: '{accessKeyId}', // Temporary AK issued by the STS server
4 sk: '{secretAccessKey}' // Temporary SK issued by the STS server
5 },
6 sessionToken: '{sessionToken}', // sessionToken issued by the STS server
7 endpoint: 'http://bj.bcebos.com'
8};
9var client = new baidubce.sdk.BosClient(bosConfig);
Access BOS via AK/SK
- Determine the endpoint. EndPoint refers to the domain name address of the BOS service in various regions. The default domain name is Beijing:
http://bj.bcebos.com. - Provide your AK/SK credentials.
- Pass the configured settings into the BosClient.
Example code
Users can refer to the following code to create BosClient:
1let config = {
2 endpoint: 'https://bj.bcebos.com',
3 credentials: {
4 ak: <AccessKeyID>, //Your AK
5 sk: <SecretAccessKey> //Your SK
6 }
7}
8let client = new BosClient(config);
Note:
The EndPointparameter, namely the BOS endpoint, must use region-specific domain names (e.g., http://aihc.bj.baidubce.com for Beijing). If unspecified, it defaults to the Beijing regionhttp://bj.bcebos.com. BOS access domain names support both HTTP and HTTPS calling methods. To improve data security, it is recommended to usehttps://bj.bcebos.com. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md).
Configure custom domain name to access BOS
Use a custom domain name
If you want to use a custom domain name as the endpoint to access BOS, after binding the custom domain name to a BOS bucket in the console, configure the endpoint as the custom domain name and turn on the cname_enabled switch, such as cdn-test.cdn.bcebos.com. The configuration code is as follows:
1var sdk = require('@baiducloud/sdk');
2var BosClient = sdk.BosClient;
3var config = {
4 credentials: {
5 ak: 'ak', //Your AK
6 sk: 'sk' //Your SK
7 },
8 endpoint: 'http://cdn-test.cdn.bcebos.com', // Custom domain name
9 cname_enabled: true // Flag for using custom domain name
10};
Configure the access domain name style
Supported by @baiducloud/sdk@1.0.1-beta.9 and above versions
The JavaScript SDK uses the virtual hosting style by default for access domain names in versions 1.0.1-beta.9 and above. If you wish to continue using the PathStyle style endpoint, you can enable it by setting pathStyleEnable to true (not recommended). For specific domain name style regulations, please refer to Bucket Domain Name Request Style
1var sdk = require('@baiducloud/sdk');
2var BosClient = sdk.BosClient;
3var config = {
4 credentials: {
5 ak: 'ak', //Your AK
6 sk: 'sk' //Your SK
7 },
8 endpoint: 'https://bj.bcebos.com', // Domain name
9 pathStyleEnable: true // Flag for using pathStyle
10};
Configure custom signature function
Supported by @baiducloud/sdk@1.0.1-beta.4and above versions
The JavaScript SDK supports authentication via STS (Security Token Service) temporary authorization. The server generates a set of temporary AK/SK with specific operation permissions and a certain timeliness. These temporary AK/SK can be exposed to the browser side for direct use. Users only need to use the createSignature signature function and calculate the latest signature using the temporary AK, SK, and sessionToken to access BOS resources. For an introduction to STS, please refer to Temporary Authorization Access.
createSignature function signature:
1import type {HttpClient} from '@baiducloud/sdk';
2 // Custom signature function
3interface SignatureFunction {
4 (
5 /* Current global authentication key */
6 credentials: {
7 ak: string;
8 sk: string
9 },
10 /* Method of the current HTTP request, GET, POST, PUT, DELETE, HEAD */
11 httpMethod: string,
12 /* Path of the current HTTP request */
13 path: string,
14 /* Query string of the current HTTP request */
15 params: Record<string, any>,
16 /* Request headers of the current HTTP request */
17 headers: Record<string, any>,
18 /* Context of the current function, usually an HttpClient instance */
19 context: HttpClient
20 ): Promise<string>;
21}
HttpClient.updateConfigByPath can be used to update the global BceConfig, and can be called via context.updateConfigByPath in SignatureFunction. Note that this function will directly modify the config on the current service instance. Do not break the original object reference to avoid invalidation of SignatureFunction. The function signature is as follows:
1interface UpdateGlobalConfigFunction {
2 (
3 /* Key path of the property to be set, such as "sessionToken", "credentials.ak", etc. */
4 path: string;
5 /* Updated value */
6 value: string,
7 ): void;
8}
Operation steps are as follows:
- Use the
getSessionTokenmethod of the STS service to generate a temporary key. This step is usually done on the server side and is only for demonstration here. -
Declare the custom signature function
createSignature, which is mainly used to determine whether the current key has expired. If it has expired, you need to obtain the latest temporary key andsessionTokenagain, and update the following information:- Use the
context.updateConfigByPathmethod to update the globalak,sk, andsessionToken. - Update the value of the request header
x-bce-security-tokento the latestsessionToken. - Update the request header
x-bce-dateto the latest current time, as there may be a time difference in signature calculation on the server side.
- Use the
1import {BosClient, STS, Auth, Q} from '@baiducloud/sdk';
2(async function () {
3 const ak = '<Your Access Key>';
4 const sk = '<Your Secret Access Key>';
5 const bucket = '<Your Bucket Name>';
6 // Temporary key validity period (seconds)
7 const durationInSeconds = 3600;
8 /* Obtain temporary authentication key */
9 async function generateTempAuth() {
10 const stsClient = new STS({
11 protocol: 'https',
12 region: 'bj',
13 endpoint: 'https://sts.bj.baidubce.com',
14 credentials: {ak, sk}
15 });
16 const res = await stsClient.getSessionToken(durationInSeconds, {
17 accessControlList: [
18 {
19 // Limit the service scope to BOS
20 service: 'bce:bos',
21 // bucket represents that the operation object is a bucket
22 // bucket/* represents that the operation object is all objects in the bucket
23 resource: [bucket, `${bucket}/*`],
24 region: 'bj',
25 effect: 'Allow',
26 permission: ['READ', 'WRITE', 'LIST']
27 }
28 ]
29 });
30 return res.body;
31 }
32 let {
33 accessKeyId,
34 secretAccessKey,
35 sessionToken,
36 expiration: expiredUTCTime
37 } = await generateTempAuth();
38 /**
39 * Signature calculation function, only for demonstration here
40 */
41 async function createSignature(
42 credentials: {ak: string; sk: string},
43 httpMethod: string,
44 path: string,
45 params: Record<string, any>,
46 headers: Record<string, any>,
47 context: any
48 ) {
49 let upatedAK = credentials.ak;
50 let upatedSK = credentials.sk;
51 const now = new Date();
52 // Round up the current number of seconds, because the expiration returned by the getSessionToken API does not have milliseconds
53 if (now.getUTCMilliseconds() > 0) {
54 // If there are milliseconds, add one second and set milliseconds to 0
55 now.setUTCSeconds(now.getUTCSeconds() + 1, 0);
56 }
57 // If the current time is greater than the expiration time, re-obtain the temporary key
58 if (now >= new Date(expiredUTCTime)) {
59 const tempRes = await generateTempAuth();
60 // Update temporary key, expiration time, and sessionToken
61 upatedAK = tempRes.ak;
62 upatedSK = tempRes.sk;
63 expiredUTCTime = tempRes.expiration;
64 sessionToken = tempRes.sessionToken;
65 // Update global config information
66 context.updateConfigByPath('credentials.ak', upatedAK);
67 context.updateConfigByPath('credentials.sk', upatedSK);
68 context.updateConfigByPath('sessionToken', sessionToken);
69 }
70 // Update session Token
71 headers['x-bce-security-token'] = sessionToken;
72 The current time, following the ISO 8601 standard, with a format like 2016-04-06T08:23:49Z.
73 const revisionTimestamp = Date.now() + (context?.timeOffset || 0);
74 headers['x-bce-date'] = new Date(revisionTimestamp).toISOString().replace(/\.\d+Z$/, 'Z');
75 // Calculate the latest signature and return it in string format
76 return Q.fcall(function () {
77 var auth = new Auth(upatedAK, upatedSK);
78 return auth.generateAuthorization(httpMethod, path, params, headers, revisionTimestamp / 1000);
79 });
80 }
81 // Generate BOS SDK service instance
82 const bosClient = new BosClient({
83 protocol: 'https',
84 endpoint: 'https://bj.bcebos.com',
85 credentials: {
86 ak: accessKeyId,
87 sk: secretAccessKey
88 },
89 sessionToken: sessionToken,
90 createSignature
91 });
92})();
Dynamically switch endpoint
Supported by @baiducloud/sdk@1.0.1-beta.9and above versions
The JavaScript SDK supports dynamically switching endpoints when calling APIs. There are two options for users:
- Provide the
regionattribute as a property of the config parameter in options to switch endpoints - Provide a custom function
customGenerateUrlthat returns the request endpoint as a property of the config parameter in options, wherecustomGenerateUrlcan use the parametersbucketNameandregion
createSignature function signature:
1import {BosClient} from '@baiducloud/sdk';
2 // Generate BOS SDK service instance
3const bosClient = new BosClient({
4 protocol: 'https',
5 endpoint: 'https://bj.bcebos.com',
6 credentials: {
7 ak: accessKeyId,
8 sk: secretAccessKey
9 },
10});
11
12 // Provide region to update endpoint
13bosClient.getBucketStorageclass(CDBucket, {config: {region: 'cd'}}).then(res => {
14 // do something
15}).catch(err => {})
16 // Custom URL generation function
17const customGenerateUrl = function (bucketName, region) {
18 const protocol = 'https';
19 return `${protocol}://${bucketName}.${region}.bcebos.com`;
20}
21bosClient.getBucketStorageclass(CDBucket, {config: {customGenerateUrl: customGenerateUrl}}).then(res => {
22 // do something
23}).catch(err => {})
