无法在我的本地主机上连接 web3.js

问题描述 投票:0回答:1

这是我的项目详细信息: 我正在构建简单的项目来将数据从表单存储到以太坊区块链。 我已经使用npm安装了nodejs、web3。 我使用的是网页版4.3.0。

我在本地环境中使用 Ganache,但无法将 ETH 导入 chrome 上的元掩码。我手动添加网络仍然显示 0 ETH。

对于合约,我使用了 remix.ethereum.org。 (这个做完了。) 无法在本地主机(XAMPP)上运行我的项目

这是我的代码:

对于 Index.html

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Waste Management System</title>
</head>
<body>
    <h1>Waste Management System</h1>
    <form action="process.php" method="post">
        <label for="wasteType">Waste Type:</label>
        <input type="text" id="wasteType" name="wasteType" required><br>

        <label for="weight">Weight:</label>
        <input type="number" id="weight" name="weight" required><br>

        <input type="submit" value="Submit">
    </form>

    <!--script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/commonjs/web3.min.js"></script-->
    <script type="module" src="interact.js"></script>
</body>
</html>

对于process.php

<?php
// process.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $wasteType = $_POST["wasteType"];
    $weight = $_POST["weight"];

    // Perform any necessary processing or validation

    // Redirect to success.php
    header("Location: success.php");
    exit();
} else {
    // Invalid request method
    echo "Invalid request method";
}
?>

成功.php

<!-- success.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Success</title>
    <!--script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/commonjs/web3.min.js"></script-->
     <script type="module" src="interact.js"></script>
</head>
<body>
    <h2>Waste Records</h2>

    <?php
    // Check if the data has been successfully added
    if (isset($_GET['success'])) {
        if ($_GET['success'] == 'true') {
            echo '<p style="color: green;">Waste data added successfully!</p>';
        } elseif ($_GET['success'] == 'false') {
            echo '<p style="color: red;">Failed to add waste data. Please try again.</p>';
        }
    }
    ?>

    <a href="index.html">Back to Form</a>

    <table id="wasteTable">
        <tr>
            <th>User</th> 
            <th>Waste Type</th>
            <th>Weight</th>
            <th>Timestamp</th>
        </tr>
    </table>

    <script>
        // Fetch waste records and update the table
        async function fetchWasteRecords() {
            const response = await fetch('/getWasteRecords');
            const records = await response.json();

            const table = document.getElementById('wasteTable');
            records.forEach(record => {
                const row = table.insertRow(-1);
                const userCell = row.insertCell(0);
                const wasteTypeCell = row.insertCell(1);
                const weightCell = row.insertCell(2);
                const timestampCell = row.insertCell(3);

                userCell.textContent = record.user;
                wasteTypeCell.textContent = record.wasteType;
                weightCell.textContent = record.weight;
                timestampCell.textContent = new Date(record.timestamp * 1000).toLocaleString();
            });
        }

        // Call the function when the page loads
        fetchWasteRecords();
    </script>
</body>
</html>

用于interact.js

// interact.js

import Web3 from 'web3.js';

// Connect to your Ethereum node
const web3 = new Web3('http://localhost:7545'); // Update with your Ethereum node URL

// Check if connected to the Ethereum node
if (web3 && web3.currentProvider && web3.currentProvider.connected) {
    console.log('Connected to Ethereum node:', web3.currentProvider.host);
} else {
    console.error('Failed to connect to Ethereum node. Please check your node URL.');
    process.exit(1); // Exit the script with an error code
}

console.log('Connecting to Ethereum node...');

const contractAddress = 'MY_contract_address'; // Replace with your deployed contract address
const contractABI = [
    
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "internalType": "address",
                "name": "user",
                "type": "address"
            },
            {
                "indexed": false,
                "internalType": "string",
                "name": "wasteType",
                "type": "string"
            },
            {
                "indexed": false,
                "internalType": "uint256",
                "name": "weight",
                "type": "uint256"
            },
            {
                "indexed": false,
                "internalType": "uint256",
                "name": "timestamp",
                "type": "uint256"
            }
        ],
        "name": "WasteAdded",
        "type": "event"
    },
    {
        "constant": false,
        "inputs": [
            {
                "internalType": "string",
                "name": "_wasteType",
                "type": "string"
            },
            {
                "internalType": "uint256",
                "name": "_weight",
                "type": "uint256"
            }
        ],
        "name": "addWasteData",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "wasteCount",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "name": "wasteRecords",
        "outputs": [
            {
                "internalType": "address",
                "name": "user",
                "type": "address"
            },
            {
                "internalType": "string",
                "name": "wasteType",
                "type": "string"
            },
            {
                "internalType": "uint256",
                "name": "weight",
                "type": "uint256"
            },
            {
                "internalType": "uint256",
                "name": "timestamp",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
];

// Initialize the contract instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Get form data from index.html
const form = document.querySelector('form');
form.addEventListener('submit', async function (event) {
    event.preventDefault();

    const wasteType = document.getElementById('wasteType').value;
    const weight = document.getElementById('weight').value;

    // Get the first account (you may need to handle accounts differently in production)
    const accounts = await web3.eth.getAccounts();

    // Call the addWasteData function on the smart contract
    await contract.methods.addWasteData(wasteType, weight).send({ from: accounts[0] });

    // Redirect to success.php with a success parameter
    window.location.href = 'success.php?success=true';
});

我在控制台上遇到错误: 未捕获的类型错误:无法解析模块说明符“web3.js”。相对引用必须以“/”、“./”或“../”开头。

javascript node.js ethereum blockchain web3js
1个回答
0
投票

您使用以太坊区块链和网络技术的废物管理系统项目似乎结构良好。您遇到的错误与您在 interact.js 文件中导入 Web3.js 的方式有关。以下是问题的详细信息以及解决方法:

错误说明

错误:未捕获类型错误:无法解析模块说明符“web3.js”。此错误是由浏览器中处理模块的方式造成的。在浏览器环境中使用 ES6 模块导入(import 语句)时,模块的路径需要是完整或相对 URL。

解决方案

  1. 正确的导入语句:您应该使用相对路径或完整 URL,而不是 import Web3 from 'web3.js';。由于您使用的是通过 npm 安装的包,因此您通常需要一个构建步骤(使用 Webpack 或 Parcel 等工具)来捆绑 JavaScript 以供浏览器使用。不过,为了快速测试,您可以直接使用 CDN 链接。

  2. 使用 CDN 进行快速修复:为了快速解决此问题以进行测试,您可以通过 CDN 导入 Web3.js。注释掉 interact.js 中的 import 语句,并将 Web3.js 脚本包含在 HTML 文件(index.html 和 success.php)中,如下所示:

<script src="https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js"></script>

然后,在interact.js中,您可以直接使用Web3,因为它是全局可用的,如下所示:

// interact.js
// No need to import here, as Web3 is included via a script tag in HTML

// Connect to your Ethereum node
const web3 = new Web3('http://localhost:7545'); // ...
  1. 生产构建工具:对于生产构建,您通常会使用 Webpack 等模块捆绑器来捆绑 JavaScript 文件。该工具负责解析 npm 包导入并将所有内容捆绑到可以提供给浏览器的文件中。

  2. MetaMask 和 Ganache:关于在 Chrome 上将 ETH 导入 MetaMask 的问题,请确保 Ganache 正在运行且配置正确。然后,在 MetaMask 中,确保您已连接到正确的网络(运行 Ganache 的网络)。通常,Ganache 会为您提供预加载 ETH 的账户列表用于测试,您需要使用这些账户的私钥将这些账户导入到 MetaMask 中。

  3. 在本地主机上运行:对于使用 XAMPP 在本地主机上运行项目,请确保您的 XAMPP 服务器正在运行并正确配置为为您的项目文件提供服务。您可能需要将您的项目放在 XAMPP 的 htdocs 目录中,然后通过 http://localhost/your_project_folder 访问它。

通过解决模块导入问题并确保您的环境设置正确,您应该能够继续您的项目。请记住,对于健壮且安全的应用程序,请考虑更高级的构建设置以及私钥和帐户的正确处理,尤其是从开发环境转移到生产环境时。

© www.soinside.com 2019 - 2024. All rights reserved.