如何解决IBM Cloud Functions Calling API with authentication / node.js
对于阅读本文的大多数人来说,这无疑是最基本的问题,并且在 2 分钟内完成。 也许有人有时间为我提供代码,或者可以推荐一个资源,为绝对初学者解释这一点。
我从 IBM 视频教程中得到了这段代码,我可以调用任何开放的 API:
let rp = require('request-promise')
function main(params) {
if (params.actionA == 'joke') {
const options = {
uri: "http://api.icndb.com/jokes/random",json: true
}
return rp(options)
.then(res => {
return { response: res }
})
} else if (params.actionB == 'fact') {
const options = {
uri: "https://catfact.ninja/fact",json: true
}
return rp(options)
.then(res => {
return { response: res }
})
}
}
我想保留笑话 API,但想用这个鼓舞人心的报价 API(需要验证)交换 Cat 事实 API:https://english.api.rakuten.net/HealThruWords/api/universal-inspirational-quotes/details
我可以从乐天获取这个node.js代码来调用quote api。
var http = require("https");
var options = {
"method": "GET","hostname": "healthruwords.p.rapidapi.com","port": null,"path": "/v1/quotes/?id=731&t=Wisdom&maxR=1&size=medium","headers": {
"x-rapidapi-host": "healthruwords.p.rapidapi.com","x-rapidapi-key": "api key here","useQueryString": true
}
};
var req = http.request(options,function (res) {
var chunks = [];
res.on("data",function (chunk) {
chunks.push(chunk);
});
res.on("end",function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
如何将其合并到 if 函数中?我想将该功能与 watson Assistant 一起使用,它适用于当前代码。我只需要quote api交换的catfact api。
解决方法
您提供的两个代码片段使用不同的模块来执行 http 请求。这可能就是它看起来有点复杂的原因。
以您所描述的方式更改行为的第一步是将 else 分支中的完整选项替换为您第二个代码片段中的选项。
第二步是为引用 URL 提供必要的 api 密钥作为函数的参数。
在向函数添加附加参数 test
后,您能否尝试一下下面的代码片段。我没有测试下面的代码,但我会这样做。如果它对您有用,请告诉我,我可以根据您的反馈改进答案。
apiKey
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。