简体   繁体   中英

Call JSON-RPC using nodejs

I am trying to call json-rpc call through request module of nodejs.

json-rpc call is in following format

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/

How to call such json-rpc call using request npm package of nodejs ??

Here's a script that will make the call using the request module:

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);
    }
});

And then call like so:

node index.js username password

You could also use environment variables to pass the username/password.

The --auth argument passed to Curl specifies Basic authentication (as implemented in the script)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM