我试图通过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的请求 npm包调用这样的json-rpc调用?
答案 0 :(得分:0)
这是一个使用请求模块进行调用的脚本:
<强> 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参数指定基本身份验证(在脚本中实现)