【问题标题】:NodeJS POST Request Over JSON-RPC通过 JSON-RPC 的 NodeJS POST 请求
【发布时间】:2015-11-03 02:34:57
【问题描述】:

我正在尝试在我的 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();
})

【问题讨论】:

    标签: json node.js rest json-rpc ethereum


    【解决方案1】:

    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 请求吗?谢谢!
    【解决方案2】:

    您缺少--header 选项:

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

    【讨论】:

      【解决方案3】:

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

      --rpcapi "personal,eth,web3"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-20
        • 2017-05-04
        • 2011-05-03
        • 2017-06-28
        • 1970-01-01
        相关资源
        最近更新 更多