文章目录
前言
本次博客简单记录下开发DApp过程中遇到的一些问题,以及相应的解决方案,因此写的也是很随意,仅供参考
Vue如何使用Web3
- 安装
Web3的依赖npm install web3@^0.20.0 --save - 项目里创建全局
web3对象- 写一个插件,例如命名为
Web3.jsimport Web3 from "web3" export default { install: function (Vue, options) { var web3 = window.web3 if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider) } else { web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')) } Vue.prototype.$web3 = web3 } } - 在
main.js里启用该插件,以后就可以这样使用this.$web3这个全局对象了Vue.use(Web3)
- 写一个插件,例如命名为
- 例子
- 获得第一个区块的信息
// 获得第一个区块的信息 this.$web3.eth.getBlock(0) // 在控制台输出相应信息 console.log(this.$web3.eth.getBlock(0))
- 获得第一个区块的信息
- 参考链接 - 基于Vue、web3的以太坊项目开发及交易内幕初探
创建账号失败问题
此处Web3.js 1.0与0.2的API混用了,没有搞清楚不同版本的区别
-
创建用户写法
this.$web3.eth.personal.newAccount('sysu',(err, accounts) => { console.log(accounts, err) }) -
报错
Uncaught TypeError: Cannot read property 'newAccount' of undefined at <anonymous>:1:19控制台再次尝试同样结果,内心崩溃

-
搜寻许久,发现
web3下面使用创建用户的模式应该为this.$web3.personal.newAccount('sysu', (err, addr) => { console.log(err) })即
personal不是在eth命名空间下,与在geth中的控制台使用有所区别 -
问题仍然没有解决,还是报错了
The method personal_newAccount does not exist/is not available] undefine
-
继续查找解决方案
Are you running with code from the Geth console or from an external JavaScript environment? If you connect an external environment to Geth via the HTTP-RPC interface, by default the personal namespace is not available due to security considerations.
发现问题所在,默认情况下,
personal由于安全考虑,命名空间不可用 -
解决方案
Run your node with --rpc and --rpcapi personal,web3 flags. i.e. geth --dev --rpcapi personal,web3,eth --rpc You may need to add --rpccorsdomain "<your-domain>", in case you are using web3 in the web. geth --dev --rpcapi personal,web3,eth --rpccorsdomain "your-domain"参照dalao的提示,使用
geth启动私有链的时候需要加入--rpcapi personal,web3,ethgeth -datadir myData/00 -networkid 2018 -rpc -rpcapi personal,web3,eth --rpcport "8545" --port "30303" -rpcaddr YOUR_IP -rpccorsdomain "*" console然后再次测试

Web3.js 0.2XX版本 与 Web3.js 1.0版本
- Web3.js 0.2x.x API 中文版手册
- Web3.js 1.0 中文手册
- 二者关于
API的使用有较多的区别,不能混用。个人后面发现Web3.js 1.0更加好用,然后就果断上车了
Remix连接私有链出现的问题
问题1: Not possible to connect to the Web3 provider
Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

错误原因: 在使用geth启动私有链结点的时候没有--rpc
解决:
geth -datadir myData/00 -networkid 2018 -rpc -rpcapi personal,web3,eth,net --rpcport "8545" --port "30303" -rpcaddr 127.0.0.1 -rpccorsdomain "*" console
加入以后可以正常连接了
问题2: 成功连接后显示can't detect network

错误原因: 在使用geth启动私有链结点的时候没有zding开启net
解决:
geth -datadir myData/00 -networkid 2018 -rpc -rpcapi personal,web3,eth,net --rpcport "8545" --port "30303" -rpcaddr 127.0.0.1 -rpccorsdomain "*" console
DApp开发挑战
本文记录了使用Vue与Web3开发DApp过程中遇到的问题与解决方案,包括Web3版本差异、创建账号失败、Remix连接私有链等常见难题。
6876

被折叠的 条评论
为什么被折叠?



