我使用Ganache在http://127.0.0.1:7545上运行了一个本地区块链。 区块链上有8个区块,没有一个是挂起的。
我在nodejs中制作了一个脚本,它使用web3从块中获取数据,但由于某种原因,它无法工作。
脚本如下:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
console.log(web3.eth.getBlockNumber())
var block = web3.eth.getBlock('latest')
console.log(block)
var firstblock = web3.eth.getBlock(0)
console.log(firstblock)
console.log(firstblock.hash)
这是脚本执行输出
>node script.js
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
undefined
getBlock
方法总是返回一个承诺。 如果希望访问block对象,则应添加.then()
。 所以应该是这样的:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
web3.eth.getBlockNumber().then(console.log)
var block = web3.eth.getBlock('latest')
block.then(console.log)
var firstblock = web3.eth.getBlock(0)
firstblock.then(console.log)
firstblock.then( block => console.log(block.hash))