Integrate Alibaba Cloud SDK V2.0 for Node.js

Updated at: 2025-03-31 07:28

To facilitate API calls, we recommend that you integrate with Alibaba Cloud SDK in your project. SDKs simplify the development process, quickly integrate features, and greatly reduce the O&M cost. To integrate with Alibaba Cloud SDK, perform the following steps: install Alibaba Cloud SDK, configure an access credential, and write code for calling API operations. This topic describes how to integrate with Alibaba Cloud SDK.

Prerequisites

The Node.js version is 8.x or later.

1. Install the SDK for Node.js

  1. Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.

  2. On the Short Message Service page, select TypeScript in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.image

2. Configure an access credential

To call API operations of an Alibaba Cloud service, you must configure an access credential, such as an AccessKey pair or a Security Token Service (STS) token. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For more information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are used to record AccessKey pairs.

Configure environment variables in Linux and macOS
Configure environment variables in Windows

Configure environment variables by using the export command

Important

The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.

  • Configure the AccessKey ID and press Enter.

    # Replace <ACCESS_KEY_ID> with your AccessKey ID. 
    export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyID
  • Configure the AccessKey secret and press Enter.

    # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • Check whether the configuration is successful.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the valid AccessKey ID is returned, the environment variables are configured.

Use GUI
Use CMD
Use Windows PowerShell
  • Procedure

    If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

    On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

    Variable

    Example

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: yourAccessKeyID

    AccessKey Secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

  • Procedure

    Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:

    setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M

    /M indicates that the environment variable is of system level. You can choose not to use this parameter when you configure a user-level environment variable.

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

In PowerShell, configure new environment variables. The environment variables apply to all new sessions.

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::User)

Configure environment variables for all users. You must run the following commands as an administrator.

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

Configure temporary environment variables. The environment variables apply only to the current session.

$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"

In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the valid AccessKey pair is returned, the configuration is successful.

3. Write code for calling API operations

In this example, the SendMessageToGlobe API operation of Short Message Service (SMS) is called. For more information about SendMessageToGlobe, see SendMessageToGlobe.

3.1 Initialize a request client

In the SDK, all requests to API operations are sent from a client. Before you can an API operation, you must initialize the request client. You can use multiple methods to initialize a request client. In this example, an AccessKey pair is used to initialize a request client. For more information, see Manage access credentials.

TypeScript
JavaScript
import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';

export default class Client {

  static createClient(): Dysmsapi20180501 {
    let config = new $OpenApi.Config({
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // See https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501(config);
  }
}
const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class Client {

  static createClient() {
    let config = new OpenApi.Config({
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // See https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501.default(config);
  }
}

3.2 Create a request object

When you call an API operation to pass parameters, you must use the request object provided by the SDK. Name the request object of the API operation in the following format: <API operation name>Request. For example, the request object of the SendSms API operation is SendSmsRequest. For more information about the parameters, see the API reference. For more information about the parameters of the SendMessageToGlobe operation, see SendMessageToGlobe.

Note

If the API operation does not support request parameters, you do not need to create a request object. For example, the DescribeCdnSubList operation does not support request parameters.

TypeScript
JavaScript
 // Create request object and set required input parameters
 let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
      // Please replace with the actual recipient number.
      to: "<YOUR_VALUE>",
      // Please replace with the actual SMS content.
      message: "<YOUR_VALUE>",
    });
// Create request object and set required input parameters
let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
    // Please replace with the actual recipient number.
    to: '<YOUR_VALUE>',
    // Please replace with the actual SMS content.
    message: '<YOUR_VALUE>',
});
Note

For some API operations that require you to upload files, you can create a request object in the format of <API operation name>AdvanceRequest to pass files. The following example shows how to call the DetectBodyCount operation of Visual Intelligence API (VIAPI):

TypeScript
JavaScript
// Read the file as a fileStream stream.
    const filePath = '<FILE_PATH>';  // Replace the value with the actual file path.
    // Check the file.
    if (!fs.existsSync(filePath)) {
        console.error('The file does not exist:', filePath);
        return;
    }
    // Create a stream and listen for stream errors.
    const fileStream = fs.createReadStream(filePath).on('error', (err) => {
        console.error('File stream errors:', err);
        process.exit(1);
    });

    let detectBodyCountAdvanceRequest = new $facebody20191230.DetectBodyCountAdvanceRequest({
      imageURLObject: fileStream,
    });
    // Read the file as a fileStream stream.
    const filePath = '<FILE_PATH>';  // Replace the value with the actual file path.
    // Check the file.
    if (!fs.existsSync(filePath)) {
        console.error('The file does not exist:', filePath);
        return;
    }
    // Create a stream and listen for stream errors.
    const fileStream = fs.createReadStream(filePath).on('error', (err) => {
        console.error('File stream errors:', err);
        process.exit(1);
    });

    // Configure request parameters.
    let detectBodyCountAdvanceRequest = new facebody20191230.DetectBodyCountAdvanceRequest({
        imageURLObject: fileStream,
    });

3.3 Initiate an API request

When you use a request client to call an API operation, we recommend that you name the function in the following format: <API operation name>WithOptions. Specify <API operation name> in camel case. This function contains two parameters: the request object and the runtime parameter. The request object is created in the preceding step. The runtime parameter is used to specify the request action, such as timeout and proxy configurations. For more information, see Advanced configuration.

Note

If the API operation does not support request parameters, you do not need to specify a request object in the request. For example, you only need to specify the runtime parameter when you call the DescribeCdnSubList operation.

TypeScript
JavaScript
// Create runtime parameters.
let runtime = new $Util.RuntimeOptions({ });
// Send a request.
await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
// Create runtime parameters.
let runtime = new Util.RuntimeOptions({ });
// Send a request.
await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
Note

For some API operations that require you to upload files, specify the function in the format of <API operation name>Advance. Specify <API operation name> in camel case. The following example shows how to call the DetectBodyCount operation of VIAPI:

TypeScript
JavaScript
// Configure the runtime parameters.
let runtime = new $Util.RuntimeOptions({ });
// Initiate the request.   
await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
 // Configure the runtime parameters.
 let runtime = new Util.RuntimeOptions({ });
 // Initiate the request.   
 await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);  

3.4 Handle exceptions

Alibaba Cloud SDK V2.0 for Node.js classifies exceptions into the following types:

  • UnretryableError: In most cases, this type of exception is caused by network issues. UnretryableError is thrown if the number of retries reaches the upper limit. You can use err.data.lastRequest to obtain the request information when the exception occurs.

  • ResponseError: In most cases, this type of exception is caused by business errors.

For more information about how to handle SDK exceptions, see Exception handling.

Important

We recommend that you take proper exception handling measures, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.

Complete sample code

Sample request
Sample request that requires file upload
TypeScript
JavaScript
import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';

export default class Client {

  static createClient(): Dysmsapi20180501 {
    let config = new $OpenApi.Config({
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501(config);
  }

  static async main(): Promise<void> {
    let client = Client.createClient();
    // Create a request object and specify parameters.
    let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
      to: "<YOUR_VALUE>",
      from: "<YOUR_VALUE>",
      message: "<YOUR_VALUE>",
    });
    let runtime = new $Util.RuntimeOptions({ });
    try {
      // Initiate the request.  
      await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
    } catch (error) {
      // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
      // Return error messages.
      console.log(error.message);
      // The URL of the corresponding error diagnostics page.
      console.log(error.data["Recommend"]);
    }    
  }
}

Client.main();
const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');

class Client {

  static createClient() {
    let config = new OpenApi.Config({
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501.default(config);
  }

  static async main() {
    // Create a request object and specify parameters.
    let client = Client.createClient();
    let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
      to: '<YOUR_VALUE>',
      from: '<YOUR_VALUE>',
      message: '<YOUR_VALUE>',
    });
    let runtime = new Util.RuntimeOptions({ });
    try {
      // Initiate the request.
      await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
    } catch (error) {
      // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
      // Return error messages.
      console.log(error.message);
      // The URL of the corresponding error diagnostics page.
      console.log(error.data["Recommend"]);
      Util.default.assertAsString(error.message);
    }    
  }
}

exports.Client = Client;
Client.main();
TypeScript
JavaScript
import { default as facebody20191230 } from '@alicloud/facebody20191230'; 
import * as $facebody20191230 from '@alicloud/facebody20191230';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import * as $tea from '@alicloud/tea-typescript';
import * as fs from "fs"; 

export default class Client {

  static createClient(): facebody20191230 {
    let config = new $OpenApi.Config({
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    config.endpoint = `facebody.cn-shanghai.aliyuncs.com`;
    return new facebody20191230(config);
  }

  static async main(args: string[]): Promise<void> {
    let client = Client.createClient();

    // Read the file as a fileStream stream.
    const filePath = '<FILE_PATH>';  // Replace the value with the actual file path.
    // Check the file.
    if (!fs.existsSync(filePath)) {
        console.error('The file does not exist:', filePath);
        return;
    }
    // Create a stream and listen for stream errors.
    const fileStream = fs.createReadStream(filePath).on('error', (err) => {
        console.error('File stream errors:', err);
        process.exit(1);
    });

    let detectBodyCountAdvanceRequest = new $facebody20191230.DetectBodyCountAdvanceRequest({
      imageURLObject: fileStream,
    });
    let runtime = new $Util.RuntimeOptions({ });
    try {
      // Initiate the request.
      const res = await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
      console.log(res);
    } catch (error) {
      if (error instanceof Error) {
        console.error('Error message:', error.message);
        const data = (error as any)?.data?.Recommend;
        if (typeof data === 'string') {
          console.log('Suggestion:', data);
        }
      } 
    }    
  }

}

Client.main(process.argv.slice(2));
'use strict';
const facebody20191230 = require('@alicloud/facebody20191230');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
const fs = require('fs'); 


class Client {

  static createClient() {
    let config = new OpenApi.Config({
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });

    config.endpoint = `facebody.cn-shanghai.aliyuncs.com`;
    return new facebody20191230.default(config);
  }

  static async main(args) {
    let client = Client.createClient();
    // Read the file as a fileStream stream.
    const filePath = '<FILE_PATH>';  // Replace the value with the actual file path.
    // Check the file.
    if (!fs.existsSync(filePath)) {
        console.error('The file does not exist:', filePath);
        return;
    }
    // Create a stream and listen for stream errors.
    const fileStream = fs.createReadStream(filePath).on('error', (err) => {
        console.error('File stream errors:', err);
        process.exit(1);
    });
    // Configure request parameters.
    let detectBodyCountAdvanceRequest = new facebody20191230.DetectBodyCountAdvanceRequest({
        imageURLObject: fileStream,
    });
    let runtime = new Util.RuntimeOptions({ });
    try {
      // Initiate the request.
      const res = await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
      console.log(res);
    } catch (error) {
      // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
      // Return error messages.
      console.log(error.message);
      // The URL of the corresponding error diagnostics page.
      console.log(error.data["Recommend"]);
      Util.default.assertAsString(error.message);
    }    
  }

}

exports.Client = Client;
Client.main(process.argv.slice(2));

FAQ

  1. How do I handle the "You are not authorized to perform this operation" error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The AccessKey pair of the Resource Access Management (RAM) user does not have the permissions to call the API operation.

    Solutions: Grant the required permissions to the RAM user. For more information, see Grant permissions to a RAM user.

    For example, if the "You are not authorized to perform this operation" error is thrown by the SendMessageToGlobe API operation, create the following custom policy to grant the required permissions to the RAM user:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  2. How do I handle the "triggerUncaughtException Error: getaddrinfo ENOTFOUND" endpoint error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The API operation does not support the endpoint that you specify when you initialize the request client.

    Solutions: Specify a supported endpoint and try again. For more information, see Configure an endpoint.

  3. How do I handle the "Cannot read properties of undefined (reading 'getCredential')" or "InvalidAccessKeyId.NotFound: code: 404" AccessKey error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The AccessKey pair is not correctly passed to the request.

    Solutions: Make sure that the AccessKey pair is correctly passed when you initialize the request client. The XXX value of process.env("XXX") is obtained form the environment variable.

For more information about how to handle SDK exceptions, see FAQ.

  • On this page (1, M)
  • Prerequisites
  • 1. Install the SDK for Node.js
  • 2. Configure an access credential
  • 3. Write code for calling API operations
  • 3.1 Initialize a request client
  • 3.2 Create a request object
  • 3.3 Initiate an API request
  • 3.4 Handle exceptions
  • Complete sample code
  • FAQ
Feedback
phone Contact Us

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

alicare alicarealicarealicare