【问题标题】:Call JSON-RPC using nodejs使用 nodejs 调用 JSON-RPC
【发布时间】:2018-05-04 09:07:11
【问题描述】:
我正在尝试通过 nodejs 的请求模块调用 json-rpc 调用。
json-rpc 调用格式如下
curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getreceivedbyaddress", "params": ["1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ", 6] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/
如何使用nodejs的request npm包调用这样的json-rpc调用??
【问题讨论】:
标签:
node.js
request
json-rpc
【解决方案1】:
这是一个使用请求模块进行调用的脚本:
index.js
const request = require('request');
// User and password specified like so: node index.js username password.
let username = process.argv.length < 2 ? "default-username" : process.argv[2];
let password = process.argv.length < 3 ? "default-password" : process.argv[3];
let options = {
url: "http://localhost:8332",
method: "post",
headers:
{
"content-type": "text/plain"
},
auth: {
user: username,
pass: password
},
body: JSON.stringify( {"jsonrpc": "1.0", "id": "curltest", "method": "getreceivedbyaddress", "params": ["1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ", 6] })
};
request(options, (error, response, body) => {
if (error) {
console.error('An error has occurred: ', error);
} else {
console.log('Post successful: response: ', body);
}
});
然后像这样调用:
node index.js username password
您也可以使用环境变量来传递用户名/密码。
传递给 Curl 的 --auth 参数指定基本身份验证(在脚本中实现)