【问题标题】: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调用??

【问题讨论】:

  • google快速搜索发现这个工具curl.trillworks.com/#node,它会使用request模块将curl命令转换成对应的nodeJS代码。虽然生成的代码非常冗长,但请使用它来了解结构,然后继续实施您的解决方案。
  • 非常感谢..它的工作..你让我开心..:)
  • 或者,使用通配符 API (github.com/reframejs/wildcard-api)。

标签: 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 参数指定基本身份验证(在脚本中实现)

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2019-12-23
    • 2015-11-03
    • 1970-01-01
    相关资源
    最近更新 更多