我有一个由express生成器生成的node.js应用程序。我想使用Metamask插件注入的web3对象,但是当我尝试console.log(process.web3)时,它是未定义的。当我在浏览器的开发者控制台中键入window.web3时,它会返回web3对象。
有人知道注入web3对象的时间以及快递应用程序中我可以分配类似
的内容var web3 = process.web3;
答案 0 :(得分:1)
您是否尝试使用web3.js服务器端(在Node.js内)或客户端(在浏览器中)?看起来你正在混合这两种情况。
当浏览器加载JS库时,客户端web3.js被初始化。通常,如果您使用$(document).ready()
之类的内容,则可以访问它。
服务器端web3.js需要implicit initialization。
答案 1 :(得分:0)
您是否尝试过以下操作?我使用它连接到由metamask注入的web3。
import { default as Web3} from 'web3';
...
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
}
});
希望这有帮助