首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Web3js无法连接错误

Web3js无法连接错误
EN

Ethereum用户
提问于 2018-02-18 17:17:08
回答 2查看 746关注 0票数 0

我对以太的发展很陌生,所以很可能我做错了。我在本地运行了一个ganache,在那里部署了一个合同,我想构建一个小应用程序来熟悉这个过程。我已经为应用程序开发选择了Vue,目前我遇到了与web3连接到ganache的问题。

在我的根组件中,我创建了一个Web3实例:

代码语言:javascript
复制
const etherUri = 'http://127.0.0.1:7545'

let web3 = new Web3(Web3.currentProvider)

if (!web3.isConnected) {
    return 'Unable to connect to ethereum node at ' + etherUri
} else {
    let accounts = web3.eth.accounts
    return accounts
}

启动和运行,Metamask连接到它,没有任何问题。然而,试图从我的应用程序连接,我总是得到isConnected = false

该应用程序作为npm run dev服务器运行。控制台没有错误。

我不经常使用js,所以在我的设置中可能有一些错误。任何线索都会很感激的。提前感谢!

EN

回答 2

Ethereum用户

回答已采纳

发布于 2018-02-18 18:00:56

试试看

代码语言:javascript
复制
window.addEventListener('load', function() {

    // Checking if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
        // Use Mist/MetaMask's provider
        web3js = new Web3(web3.currentProvider);
    } else {
        console.log('No web3? You should consider trying MetaMask!')
        // fallback - use your fallback strategy (local node / hosted node +     in-dapp id mgmt / fail)
        web3js = new Web3(new Web3.providers.HttpProvider("http://    localhost:8545"));
    }

    // Now you can start your app & access web3 freely:
    startApp()

})

Web3 - Ethereum浏览器环境检查

票数 1
EN

Ethereum用户

发布于 2018-02-18 18:55:03

如果您使用的是vue,那么尝试以下操作(类似于shawn的回答):

代码语言:javascript
复制
const Web3 = require('web3');
let web3js;

export default {
created() {
  if (typeof web3 !== 'undefined') {
    web3js = new Web3(web3.currentProvider);
    // then call functions to determine account and balance
  } else {
    web3js = new Web3(new Web3.providers.HttpProvider(provider));
    // replace provider with URL of your choice
  }
},
...
};

Web3 3/Vue在Github上的实现

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/40106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档