Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS POST Request Over JSON-RPC

I am trying to execute a POST request over JSON-RPC on my NodeJS server. Converting the following curl command:

curl -X POST --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' http://localhost:8545

In NodeJS I keep receiving:

200 {"id":-1,"jsonrpc":"2.0","error":{"code":-32600,"message":"Could not decode request"}}

In the header I am specifying the Content-Type. If someone can point out what I am not specifying and how to add it in it would be much appreciated.

var headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/json-rpc',
    'Accept':'application/json-rpc'
}

var options = {
    url: "http://localhost:8545",
    method: 'POST',
    headers: headers,
    form: {"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":1}
}

request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        res.writeHeader(200, {"Content-Type": "text/plain"});
        res.write(res.statusCode.toString() + " " + body);
    }else{
      res.writeHeader(response.statusCode, {"Content-Type": "text/plain"});
      res.write(response.statusCode.toString() + " " + error);
    }
    res.end();
})
like image 323
BDGapps Avatar asked Jul 05 '26 15:07

BDGapps


2 Answers

form is for application/x-www-url-encoded requests, not JSON. Try these options instead:

var options = {
  url: "http://localhost:8545",
  method: 'POST',
  headers: headers,
  body: JSON.stringify({
    jsonrpc: '2.0',
    method: 'personal_newAccount',
    params: ['pass'],
    id: 1
  })
}

You can also set json: true in your options to have request automatically parse the response as JSON.

like image 179
mscdex Avatar answered Jul 07 '26 08:07

mscdex


You're missing the --header option:

curl --request POST \
    --header 'Content-type: application/json' \
    --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' \
    http://localhost:8545
like image 27
Beau Barker Avatar answered Jul 07 '26 09:07

Beau Barker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!