以太坊 Web3.js 无效的 JSON RPC 响应:" "



我正在为以太坊使用web3.js模块。在执行事务时,我收到错误响应。

错误:

"Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (/home/akshay/WS/ethereum/node_modules/web3-core-helpers/src/errors.js:42:16)
at XMLHttpRequest.request.onreadystatechange (/home/akshay/WS/ethereum/node_modules/web3-providers-http/src/index.js:73:32)
at XMLHttpRequestEventTarget.dispatchEvent (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)"

我正在使用ropsten测试网络url来测试我的智能合约:

https://ropsten.infura.io/API_KEY_HERE

当我调用balanceOf函数时,它工作正常,但当我尝试调用函数transfer时,它会向我发送此错误。代码如下所述:

router.post('/transfer', (req, res, next)=>{
contractInstance.methods.transfer(req.body.address, req.body.amount).send({from:ownerAccountAddress})
.on('transactionHash',(hash)=>{
console.log(hash)
}).on('confirmation',(confirmationNumber, receipt)=>{
console.log(confirmationNumber)
console.log(receipt)
}).on('receipt', (receipt)=>{
console.log(receipt)
}).on('error',(err)=>{
console.log(err)
})
})

请告诉我哪里错了。

编辑:我使用的是web3js版本"web3": "^1.0.0-beta.34"

要添加maptuhec所说的内容,在Web3中调用"状态更改"函数或状态更改事务时,必须对其进行签名!

下面是一个例子,当你试图调用一个公共函数(甚至是一个公共合同变量(时,它只是从你的智能合同中读取(或"查看"(并返回一个值,而不改变它的状态,在这种情况下,我们不必指定一个交易主体,然后将其作为交易进行签名,因为它不会改变我们合同的状态。

contractInstance.methods.aPublicFunctionOrVariableName().call().then( (result) => {console.log(result);})

**

状态更改事务

**

现在,考虑下面的例子,在这里我们试图调用一个"状态更改"函数,因此我们将为它指定一个适当的事务结构

web3.eth.getTransactionCount(functioncalleraddress).then( (nonce) => {
let encodedABI = contractInstance.methods.statechangingfunction().encodeABI();
contractInstance.methods.statechangingfunction().estimateGas({ from: calleraddress }, (error, gasEstimate) => {
let tx = {
to: contractAddress,
gas: gasEstimate,
data: encodedABI,
nonce: nonce
};
web3.eth.accounts.signTransaction(tx, privateKey, (err, resp) => {
if (resp == null) {console.log("Error!");
} else {
let tran = web3.eth.sendSignedTransaction(resp.rawTransaction);
tran.on('transactionHash', (txhash) => {console.log("Tx Hash: "+ txhash);});

有关signTransaction、sendSignedTransaction、getTransactionCount和estimateGas 的更多信息

使用Web3.js时,应该对事务进行签名。当您调用非常量函数(如transfer(时,您应该对事务进行签名,然后发送签名的事务(有一种方法称为sendSignedTransaction(。使用web3js非常困难,我建议使用ehtersjs,有了它,一切都变得容易多了。

在我的情况下,这是网络问题。

我在终端中设置了HTTP_PROXYHTTPS_PROXY,可以成功地设置curl google.com,但我遇到了这个错误。

解决方案:

我ssh到另一台服务器(位于香港,那里的网络可以很好地连接世界各地(,一切都很好。

最新更新