Use Alibaba Cloud SDK for Node.js with an IDE

更新时间:
复制 MD 格式

Use Alibaba Cloud SDK for Node.js in Visual Studio Code (VS Code) on Windows.

Prerequisites

Use the SDK

Use the sample project from OpenAPI Portal

Note

If OpenAPI Portal fails to download the sample project, try Use the SDK in an existing project.

  1. Go to the API Debugging page in the OpenAPI Portal. Select a cloud product and API. This example uses the ECS DescribeRegions API. Enter DescribeRegions in the search bar and click the API name.

    image

  2. On the Parameter Settings tab, enter the required parameters. The Document tab on the right provides the API description, notes, billing information, and parameter details.

    The DescribeRegions API supports three parameters:

    Parameter name

    Required

    Description

    InstanceChargeType

    Optional

    Supported regions vary by billing method. Default: PrePaid.

    ResourceType

    Optional

    Supported regions vary by resource type. Default: instance.

    AcceptLanguage

    Optional

    Language of returned results. Default: zh-CN.

    image

  3. On the SDK Sample tab on the right, select a language. Click the Download Project button to download the complete SDK project to your local computer and decompress it.

    image

  4. Open VS Code. In the menu bar, click File > Open Folder. Select the decompressed folder.

  5. In the VS Code menu bar, click Terminal > New Terminal.

    image

  6. In the Terminal, run the following command to install TypeScript.

     npm install -g typescript
  7. In the Terminal, run the following command to install project dependencies.

    npm install
  8. In the Terminal, run the following command to compile TypeScript files into JavaScript. The output files are placed in the dist directory.

    tsc
  9. In the Terminal, run the following command to execute the sample code.

    node ./dist/client.js
  10. Verify the result. Press Ctrl+F in the Terminal and search for statusCode. A "statusCode": 200 response indicates success.

    image

Use the SDK in an existing project

  1. Open VS Code. Click File > Open Folder and create or select a project folder, such as tssdkproject.

  2. In the VS Code menu bar, click Terminal > New Terminal.

    image

  3. Obtain the SDK.

    Go to SDK Center. Select a cloud product, such as ECS. Set SDK Version to V2.0 and Language to TypeScript.

    image

  4. Install the SDK.

    Copy the installation command into the Terminal and press Enter to run it.

    image

  5. Create a file. Next to the project name, click the New File icon and enter a file name, such as ecsDescribeRegions.js.

    image

  6. Initialize the client.

    Initialize an ECS client before calling any ECS API.

    Important
    1. You must use an AccessKey for identity verification when you initialize the client. For information about how to obtain an AccessKey, see Create an AccessKey.

    2. After you obtain the AccessKey for the RAM user, you must set the AccessKey in the environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

    3. For information about how to set the endpoint, see Endpoints.

    // Import the ECS client and the OpenAPI client.
    const ecs20140526 = require('@alicloud/ecs20140526');
    const openapiclient = require('@alicloud/openapi-client');
    
    /**
     * Initialize the ECS client configuration.
     * This configuration uses the Access Key ID and Access Key Secret from environment variables for authentication and sets the endpoint to ecs.cn-hangzhou.aliyuncs.com.
     */
    const ecsconfig = new openapiclient.Config();
    ecsconfig.accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID; // Get the Access Key ID from environment variables.
    ecsconfig.accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET; // Get the Access Key Secret from environment variables.
    ecsconfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'; // Set the endpoint for the ECS service.
    
    // Create a client instance for ECS API version 20140526.
    const ecs20140526client = new ecs20140526.default(ecsconfig);
    
  7. Call the API. Review the API Documentation for the target API. The following example calls the `DescribeRegions` API of ECS.

    Note

    Each API has a separate request object that follows the `${APIName}${Request}` naming convention, such as `DescribeRegionsRequest`.

    // Import the ECS client and the OpenAPI client.
    const ecs20140526 = require('@alicloud/ecs20140526');
    const openapiclient = require('@alicloud/openapi-client');
    
    /**
     * Initialize the ECS client configuration.
     * This configuration uses the Access Key ID and Access Key Secret from environment variables for authentication and sets the server-side endpoint to ecs.cn-hangzhou.aliyuncs.com.
     */
    const ecsconfig = new openapiclient.Config();
    ecsconfig.accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID; // Use the Access Key ID from environment variables.
    ecsconfig.accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET; // Use the Access Key Secret from environment variables.
    ecsconfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'; // Set the endpoint for the ECS service.
    
    // Create a client instance for ECS API version 20140526.
    const ecs20140526client = new ecs20140526.default(ecsconfig);
    const describeRegionsRequest = new ecs20140526.DescribeRegionsRequest();
    // Initiate a request to query all regions.
    ecs20140526client.describeRegions(describeRegionsRequest).then((res)=>{
        console.log(res);
    })
    
    
  8. Handle exceptions.

    The Node.js V2.0 SDK throws two types of exceptions: business exceptions (service errors) and network exceptions (thrown after max retries). The sample code does not differentiate between them because the exception classes cannot be imported from external modules.

    // Import the ECS client and the OpenAPI client.
    const ecs20140526 = require('@alicloud/ecs20140526');
    const openapiclient = require('@alicloud/openapi-client');
    
    /**
     * Initialize the ECS client configuration.
     * This configuration uses the Access Key ID and Access Key Secret from environment variables for authentication and sets the server-side endpoint to ecs.cn-hangzhou.aliyuncs.com.
     */
    const ecsconfig = new openapiclient.Config();
    ecsconfig.accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID; // Use the Access Key ID from environment variables.
    ecsconfig.accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET; // Use the Access Key Secret from environment variables.
    ecsconfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'; // Set the endpoint for the ECS service.
    
    // Create a client instance for ECS API version 20140526.
    const ecs20140526client = new ecs20140526.default(ecsconfig);
    const describeRegionsRequest = new ecs20140526.DescribeRegionsRequest();
    // Initiate a request to query all regions.
    ecs20140526client.describeRegions(describeRegionsRequest).then((res) => {
        console.log(res);
    }).catch((err) => {
        console.log(err.message);
        throw err;
    });
    
  9. Run the sample code.

    1. If Code Runner is installed, right-click in the editor and select Run Code.

      image

    2. Run the file with the node command, for example, node .\ecsDescribeRegions.js.

      image

    3. Click Run and Debug in the sidebar or press Ctrl+Shift+D, then click Run and Debug to run the active file.

      image

  10. (Optional) Copy sample code from OpenAPI Portal into a file and run it. Automatic SDK code generation.

References

Further reading