NodeJS通过JSON-RPC进行POST请求

3

我将在我的NodeJS服务器上通过JSON-RPC执行一个POST请求。将以下curl命令转换为代码:

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

在NodeJS中,我一直收到以下信息:
200 {"id":-1,"jsonrpc":"2.0","error":{"code":-32600,"message":"Could not decode request"}}

在头部,我正在指定Content-Type。如果有人能指出我没有指定什么以及如何添加它,那将不胜感激。
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();
})
3个回答

3

form用于application/x-www-url-encoded请求,而非JSON。请尝试以下选项代替:

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

您可以在选项中设置json:true,使request自动将响应解析为JSON。

我似乎无法让它工作,你能看一下我试图复制的curl请求吗?谢谢! - BDGapps

2
您缺少--header选项:
curl --request POST \
    --header 'Content-type: application/json' \
    --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' \
    http://localhost:8545

0

要使用“personal_newAccount”和{{link1:Ethereum Docs}}中的其他选项,您需要启动带有所需API的服务器:

--rpcapi "personal,eth,web3"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接