更新时间:2024-02-18 GMT+08:00

JavaScript

本节以IntelliJ IDEA工具为例,介绍如何在Js环境中集成API请求签名的SDK。您可以直接导入示例工程体验,然后参考调用说明部分将签名SDK集成到您的应用中。

以搭建Node.js开发环境为例介绍JavaScript的SDK集成。

准备环境

  • 获取并安装IntelliJ IDEA,可至IntelliJ IDEA官方网站下载。
  • 获取并安装Nodejs安装包,可至Nodejs官方下载页面下载。
    NodeJs安装后,在命令行中,用npm安装“moment”和“moment-timezone”模块。
    npm install moment --save
    npm install moment-timezone --save
  • 在IDEA中安装Nodejs插件,如下图所示。

获取SDK

点此下载SDK与Demo

解压时选择解压到当前文件夹,解压后目录结构如下:

名称

说明

signer.js

SDK代码

node_demo.js

Nodejs示例代码

test.js

测试用例

licenses\license-crypto-js

第三方库license文件

licenses\license-node

创建工程

  1. 打开IDEA,选择菜单“File > New > Project”。

    弹出“New Project”对话框。选择“Static Web”,单击“Next”。

  2. 单击“...”,在弹出的对话框中选择解压后的SDK路径,单击“Finish”。

  3. 完成工程创建后,目录结构如下。

  4. 在IDEA窗口右上方,单击“Edit Configurations”或“Add Configurations”。

  5. 单击“+”,选择“Node.js”。

  6. “JavaScript file”选择“node_demo.js”,单击“OK”,完成配置。

API调用(Node.js)

  1. 在命令行中,用npm安装“moment”和“moment-timezone”模块。

    1
    2
    npm install moment --save
    npm install moment-timezone --save
    

  2. 在工程中引入signer.js。

    1
    2
    var signer = require('./signer')
    var http = require('http')
    

  3. 生成一个新的Signer,填入“Key”和“Secret”。

    1
    2
    3
    4
    5
    var sig = new signer.Signer()
    // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables.
    // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
    sig.Key = process.env.HUAWEICLOUD_SDK_AK
    sig.Secret = process.env.HUAWEICLOUD_SDK_SK
    

  4. 生成一个新的Request,指定域名、方法名、请求uri和body。

    1
    2
    3
    4
    5
    //The following example shows how to set the request URL and parameters to query a VPC list.
    var r = new signer.HttpRequest("GET", "service.region.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limie=1");
    
    //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
    r.body = '';
    

  5. 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。

    1
    2
    //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service.
    r.headers = {"X-Project-Id": "xxx"};
    

  6. 进行签名,执行此函数会生成请求参数,用于创建https请求,请求参数中添加了用于签名的X-Sdk-Date头和Authorization头。

    1
    var opt = sig.Sign(r)
    

  7. 访问API,查看访问结果。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    var req = https.request(opt, function(res){
            console.log(res.statusCode)  
            res.on("data",	function(chunk){
    		console.log(chunk.toString())
    	})
    })
    req.on("error",function(err){
    	console.log(err.message)
    })
    req.write(r.body)
    req.end()