API网关 APIG-JavaScript:调用API(Node.js)示例

时间:2023-12-25 15:22:03

调用API(Node.js)示例

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

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

  2. 生成一个新的Signer,填入AppKey和AppSecret。

    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

  3. 生成一个Request对象,指定方法名、请求uri和body。

    var r = new signer.HttpRequest("POST", "c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/app1?a=1");
    r.body = '{"a":1}'

  4. 给请求添加x-stage头,内容为环境名。如有需要,添加需要签名的其他头域。

    r.headers = { "x-stage":"RELEASE" }

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

    var opts = sig.Sign(r)

  6. 访问API,查看访问结果。如果使用https访问,则将“http.request”改为“https.request”。

    var req=http.request(opts, 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()

support.huaweicloud.com/devg-apig/apig-dev-180307018.html