node.js - 使用 node.js 在 IBM Cloud 中的 Web 操作中使用 axios
问题描述
我一直在尝试获取一个简单的 Web 操作来向 API 发出经过身份验证的 GET 请求(我已经从示例代码中删除了实际的 url 和秘密)。
我已经在本地成功运行了它,但是当我测试 web 操作时,它在记录“调用 axios”后就死了。
它不报告错误,我试图实现一个承诺,认为线程在 api 响应之前就结束了,但没有效果。任何指针?
/**
*
* main() will be run when you invoke this action
*
* @param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* @return The output of this action, which must be a JSON object.
*
*/
function main(params) {
getData().then(function(result) {
console.log("In the THEN of original method call");
return "hello";
})
.catch(function(err) {
console.log("In catch of original method call");
});
}
function getData(){
const crypto = require('crypto');
const axios = require('axios');
const secretKey = "ENTER KEY HERE";
const apiId = 99999;
const apiBaseUrl = "https://acmewebservice.com";
const apiPath = "/customer/9";
const apiFullPath = apiBaseUrl + apiPath;
const sharedSecretHash = crypto.createHash('sha256').update(secretKey).digest('hex');
console.log("In getData");
var authToken = apiId + ":" + sharedSecretHash;
return new Promise((resolve, reject) => {
console.log("Calling axios");
axios.get(apiFullPath, {
headers: {
'Authentication': authToken
}
}).then(response => {
console.log("Did this work?")
var x = JSON.stringify(response.data);
console.log(x);
resolve(response);
})
.catch(error => {
console.log("In Catch")
console.log(error);
reject(error);
});
});
解决方案
您不需要重新包装 axios 调用,它已经是一个承诺。
return
需要使引擎有效地等待异步调用的结果。
function getData(){
const crypto = require('crypto');
const axios = require('axios');
const secretKey = "ENTER KEY HERE";
const apiId = 99999;
const apiBaseUrl = "https://acmewebservice.com";
const apiPath = "/customer/9";
const apiFullPath = apiBaseUrl + apiPath;
const sharedSecretHash = crypto.createHash('sha256').update(secretKey).digest('hex');
console.log("In getData");
var authToken = apiId + ":" + sharedSecretHash;
console.log("Calling axios");
return axios.get(apiFullPath, {
headers: {
'Authentication': authToken
}
}).then(response => {
console.log("Did this work?")
var x = JSON.stringify(response.data);
console.log(x);
return response;
})
.catch(error => {
console.log("In Catch")
console.log(error);
});
推荐阅读
- android-espresso - Android Studio - 缺少 androidTest 文件夹
- dynamics-crm - 如何从 Powerapps 获取为 Office 365 环境中的用户分配的角色
- vbscript - 使用 VBscript 从 AD 中的计算机对象获取 accountexpires
- mobile - 哪些区块链项目在原生移动应用程序中运行以及实施它的挑战是什么?
- algorithm - 并发重新散列。什么是多级重新散列中的“重新散列段”?
- .net - 检测是否找到特定单词.Net
- python - 按钮生成(wx.Python、Python)
- angular - 如何聚焦使用 Angular 模型驱动表单动态创建的输入字段
- javascript - 循环只做最后一个值,但它在调试模式中做所有
- rest - 使用 RAML 规范的 REST API:如何指定响应的总页数