首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何添加此库(web3)并在我的html页面上使用?

如何添加此库(web3)并在我的html页面上使用?
EN

Stack Overflow用户
提问于 2021-11-04 16:26:44
回答 1查看 490关注 0票数 1

我有一个节点项目,我试图在一个简单的html页面上使用web3,这样用户就可以将一些东西写到一个简单的智能合约中。第1步,我只是尝试访问main.html调用的JavaScript文件中的web3对象。

下面是文件夹结构:

代码语言:javascript
运行
复制
index.js
package.json
main.html (uses main.js)
assets/
    js/
        main.js

下面的代码我用来在我的计算机上开始使用ganache测试网络:

代码语言:javascript
运行
复制
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中时,它似乎没有给出错误:

代码语言:javascript
运行
复制
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.jsmain.html上使用web3功能,因为用户将填写表单,点击按钮,然后我将使用web3功能在我的简单合同中编写一些内容。

但是我想我并不了解node.js项目的布局和结构。考虑到上面的用例,我应该如何继续?当我将web3启动器代码放在index.js中时,我不知道如何访问main.js中的web3对象。我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2021-11-04 16:35:39

您需要在.html中使用纯js文件。在头文件中添加脚本,只实例化Web3类:new Web3 ( "http://localhost:7545" )

代码语言:javascript
运行
复制
<script src="https://github.com/ChainSafe/web3.js/blob/v1.2.11/dist/web3.min.js></script>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69842611

复制
相关文章

相似问题

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