dApp:Web3.eth.getCoinbase(function(err, account) 不显示我从元掩码连接的 rinkeby 帐户

Viv*_*aud 3 heroku node.js ethereum web3js

我有一个 dApp,可以在本地 Ganache 网络上运行,但不能在 Heroku 上部署的 Rinkeby 上运行

我在 App.js 中有这段代码:

// Load account data
    web3.eth.getCoinbase(function(err, account) {
      if (err === null) {
        App.account = account;
        $("#accountAddress").html("Your Account: " + account);
      }
    });
Run Code Online (Sandbox Code Playgroud)

但这就是我得到的:您的帐户:null

这是文件:https://github.com/Louvivien/filmdevelopmentapp/blob/master/src/js/app.js

你知道我能做什么吗?

小智 10

默认情况下,Metamask 可能不会启用连接。尝试这个:

if(web3.currentProvider.enable){
    //For metamask
    web3.currentProvider.enable().then(function(acc){
        App.account = acc[0];
        $("#accountAddress").html("Your Account: " + App.account);
    });
} else{
    App.account = web3.eth.accounts[0];
    $("#accountAddress").html("Your Account: " + App.account);
}
Run Code Online (Sandbox Code Playgroud)

Metamask 将不再支持 web3js,转而支持 ethereumProvider。使用 ethereumProvider 的替代方案:

if(window.ethereum){
    ethereum.enable().then(function(acc){
        App.account = acc[0];
        $("#accountAddress").html("Your Account: " + App.account);
    });
}
Run Code Online (Sandbox Code Playgroud)

根据 MetaMask 文档,返回的帐户对象已保留为未来扩展的列表,尽管它只服务于一个帐户。

使用 MetaMask 获取所选地址的另一种简短方法:

web3.currentProvider.selectedAddress
Run Code Online (Sandbox Code Playgroud)