Todos los productos
Search
Centro de documentos

Alibaba Cloud SDK:Integrar el SDK

Última actualización: Sep 19, 2026

Integre el SDK de Alibaba Cloud en su proyecto para simplificar las llamadas a OpenAPI, acelerar la integración de funciones y reducir los costos de mantenimiento. Este tema abarca la instalación y el uso básico del SDK.

Requisitos previos

Node.js 8.x o posterior

Instalar el SDK

El SDK de Node.js V1.0 solo admite llamadas generalizadas (CommonRequest). Estas requieren únicamente la dependencia @alicloud/pop-core. Ejecute el siguiente comando para instalarla:

npm install @alicloud/pop-core

Usar el SDK

El SDK de Node.js V1.0 admite dos estilos de llamada: RPC y ROA. Los siguientes ejemplos utilizan la operación DescribeInstances de ECS para RPC y la operación DescribeClustersV1 de Container Service for Kubernetes (ACK) para ROA.

1. Inicializar el cliente de solicitud

Todas las operaciones de OpenAPI se llaman mediante RPCClient o ROAClient, que proporciona @alicloud/pop-core. Debe inicializar el cliente antes de llamar a cualquier operación. El siguiente ejemplo utiliza un par de AccessKey. Para conocer otros métodos de inicialización, consulte Initialize the client using an STS token.

Nota

El ejemplo obtiene las credenciales de variables de entorno. Antes de ejecutar el código, configure las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET. Para obtener más información, consulte Configure environment variables on Linux, macOS, and Windows systems.

Cliente RPC

// Initialize the RPC client
const Core = require('@alicloud/pop-core');
var client = new Core({
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  // The domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for ECS: http://ecs-cn-hangzhou.aliyuncs.com
  endpoint: 'https://ecs.cn-hangzhou.aliyuncs.com',
  // The API version of the cloud product. Example for ECS: 2014-05-26
  apiVersion: '2014-05-26'
});

Cliente ROA

// Initialize the ROA client
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient({
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  // The domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for Container Service: http://cs.cn-chengdu.aliyuncs.com
  endpoint: 'https://cs.cn-chengdu.aliyuncs.com',
  // The API version of the cloud product. Example for Container Service: 2015-12-15
  apiVersion: '2015-12-15'
});

2. Construir los parámetros de la solicitud

Una solicitud requiere tres parámetros: el nombre de la operación de OpenAPI, el objeto de parámetros de la solicitud y el objeto de parámetros de ejecución.

Nota

No se admite la carga de archivos locales. Para cargar un archivo local, utilice el SDK V2.0.

Parámetros de llamada RPC

// The name of the OpenAPI operation
var action = 'DescribeInstances'
// The request parameters
var params = {
  "RegionId": "cn-hangzhou",
  "InstanceIds": "[\"i-bp67************\", \"i-7xva************\", … \"i-7xvc************\"]"
}
// The runtime parameters
var requestOption = {
  method: 'POST',
  formatParams: false,
};

Parámetros de llamada ROA

// The request method
const method = "GET"
// The path parameter
const uriPattern = '/api/v1/clusters';
// The query parameters
var queryParams = {
  "cluster_type": "Kubernetes",
  "name": "cluster-demo"
};
// The request body in the JSON string format. Example: `{"nodepool_info":{"name":"nodepool-test","type":"ess"}}`;
const body = "";
// The custom request headers
const headers = {
  "Content-Type": "application/json"
};
// The runtime parameters
const options = {
  timeout: 3000, // default 3000 ms
};

3. Enviar la solicitud

Llame a la operación request del cliente creado en el paso 1 y pase los parámetros construidos en el paso 2.

Llamada RPC

// Send the request
client.request(action, params, requestOption).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

Llamada ROA

// Send the request
roaClient.request(method, uriPattern, queryParams, body, headers, options)
  .then((response) => {
    console.log('ROA Response:', response);
  })
  .catch((error) => {
    console.error('ROA Error:', error);
  });

4. Gestionar excepciones

De forma predeterminada, se lanza una excepción si el campo Code de la respuesta de la API no es 200, OK, Success ni success. Puede definir códigos de error personalizados para su programa. Para obtener más información, consulte Exception handling.

Ejemplos de código completos

Llamada RPC

// Initialize the RPC client
const Core = require('@alicloud/pop-core');

var client = new Core({
  // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  // The domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for ECS: http://ecs-cn-hangzhou.aliyuncs.com
  endpoint: 'https://ecs.cn-hangzhou.aliyuncs.com',
  // The API version of the cloud product. Example for ECS: 2014-05-26
  apiVersion: '2014-05-26'
});

// The name of the OpenAPI operation
var action = 'DescribeInstances'

// The request parameters
var params = {
  "RegionId": "cn-hangzhou",
  "InstanceIds": "[\"i-bp67acfmxazb4p****\", \"i-bp67acfmxazb4p****\", … \"i-bp67acfmxazb4p****\"]"
}

// The runtime parameters
var requestOption = {
  method: 'POST',
  formatParams: false,
};

// Send the request
client.request(action, params, requestOption).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

Llamada ROA

const ROAClient = require('@alicloud/pop-core').ROAClient;

// Initialize the ROA client
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient({
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  // The domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for Container Service: http://cs.cn-chengdu.aliyuncs.com
  endpoint: 'https://cs.cn-chengdu.aliyuncs.com',
  // The API version of the cloud product. Example for Container Service: 2015-12-15
  apiVersion: '2015-12-15'
});

// The request method
const method = "GET"
// The path parameter
const uriPattern = '/api/v1/clusters';
// The query parameters
var queryParams = {
  "cluster_type": "Kubernetes",
  "name": "cluster-demo"
};
// The request body in the JSON string format. Example: `{"nodepool_info":{"name":"nodepool-test","type":"ess"}}`;
const body = "";
// The custom request headers
const headers = {
  "Content-Type": "application/json"
};
// The runtime parameters
const options = {
  timeout: 3000, // default 3000 ms
};

// Send the request
roaClient.request(method, uriPattern, queryParams, body, headers, options)
  .then((response) => {
    console.log('ROA Response:', response);
  })
  .catch((error) => {
    console.error('ROA Error:', error);
  });

Referencias