我有一个节点项目,我试图在一个简单的html页面上使用web3,这样用户就可以将一些东西写到一个简单的智能合约中。第1步,我只是尝试访问main.html调用的JavaScript文件中的web3对象。
下面是文件夹结构:
index.js
package.json
main.html (uses main.js)
assets/
js/
main.js
下面的代码我用来在我的计算机上开始使用ganache测试网络:
const Web3 = require('web3');
const web3 = new Web3 ( "http://localhost:7545" )
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
console.log("Connected to web3");
return true;
}
alert("Error - could not connect via web3.js");
return false;
}
但是,当我将这段代码粘贴到assets/js/main.js
的顶部时,我得到了以下结果:
Uncaught ReferenceError: require is not defined at main.js:5
所以我甚至不能使用require
包,更不用说web3
包了,这两个包我都是通过npm install
安装的。
但是,当我将上面的web3代码粘贴到index.js
中时,它似乎没有给出错误:
const express = require('express')
const app = express()
const port = 3000
const Web3 = require('web3');
const web3 = new Web3 ( "http://localhost:7545" )
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
console.log("Connected to web3");
return true;
}
alert("Error - could not connect via web3.js");
return false;
}
app.use(express.static("./assets"));
app.get('/', (req, res) => {
//res.send('Hello World!')
res.sendFile('./main.html', { root: __dirname });
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
我想通过main.js
在main.html
上使用web3
功能,因为用户将填写表单,点击按钮,然后我将使用web3
功能在我的简单合同中编写一些内容。
但是我想我并不了解node.js
项目的布局和结构。考虑到上面的用例,我应该如何继续?当我将web3
启动器代码放在index.js
中时,我不知道如何访问main.js
中的web3
对象。我该怎么做呢?
发布于 2021-11-04 16:35:39
您需要在.html中使用纯js文件。在头文件中添加脚本,只实例化Web3类:new Web3 ( "http://localhost:7545" )
,
<script src="https://github.com/ChainSafe/web3.js/blob/v1.2.11/dist/web3.min.js></script>
https://stackoverflow.com/questions/69842611
复制相似问题