无法调用login.html绑定的login.js中import后定义的函数,求解决
问题分析与解决方案
核心问题1:ES模块作用域隔离导致HTML无法调用函数
用<script type="module">加载的JS文件运行在模块作用域中,函数不会自动挂载到window全局对象。HTML里的onchange="incre()"、onclick="comp()"是在全局作用域查找函数,自然无法找到。
核心问题2:重复使用export default
一个ES模块只能有一个默认导出,你在login.js里写了两个export default function,会直接触发语法错误,导致模块无法正常加载。
核心问题3:浏览器无法直接使用mysql2
mysql2是Node.js专属的数据库驱动,浏览器没有Node.js运行环境,无法直接连接MySQL数据库,必须通过后端API(比如用Express搭建接口)处理数据库查询。
修正步骤
步骤1:修复login.js的导出与作用域问题
将函数改为命名导出,同时手动挂载到window对象(或更推荐用JS绑定事件):
import { rows } from "./connect.js"; console.log(rows); let nm = 0; let pwd = 0; // 改为命名导出,删除重复的export default export function incre() { for (let i = 0; i < rows.length; i++) { if (rows[i].uname == document.getElementById("username").value) { nm++; console.log(nm); } if (rows[i].pwd == document.getElementById("pwd").value) { pwd++; } } } export function comp() { document.getElementById("but").style.marginLeft = "23px"; document.getElementById("pwd").style.marginLeft = "32px"; if (nm == 0) { document.getElementById("usernameerr").innerText = "Invalid Username"; document.getElementById("but").style.marginTop = "20px"; } if (pwd == 0) { document.getElementById("passworderr").innerText = "Invalid Password"; document.getElementById("but").style.marginTop = "20px"; } if (nm > 0 && pwd > 0) { window.location.replace("main.html"); } nm = 0; // 修正原代码中的笔误num pwd = 0; } // 将函数挂载到window,让HTML能访问 window.incre = incre; window.comp = comp;
步骤2:改用JS绑定事件(更规范的写法)
不推荐在HTML标签中写事件属性,直接在login.js中绑定事件,避免全局作用域依赖:
import { rows } from "./connect.js"; console.log(rows); let nm = 0; let pwd = 0; function incre() { nm = 0; pwd = 0; const usernameVal = document.getElementById("username").value; const pwdVal = document.getElementById("pwd").value; for (let i = 0; i < rows.length; i++) { if (rows[i].uname === usernameVal) nm++; if (rows[i].pwd === pwdVal) pwd++; } } function comp() { const but = document.getElementById("but"); const pwdInput = document.getElementById("pwd"); const usernameErr = document.getElementById("usernameerr"); const passwordErr = document.getElementById("passworderr"); but.style.marginLeft = "23px"; pwdInput.style.marginLeft = "32px"; usernameErr.innerText = ""; passwordErr.innerText = ""; but.style.marginTop = ""; if (nm === 0) { usernameErr.innerText = "Invalid Username"; but.style.marginTop = "20px"; } if (pwd === 0) { passwordErr.innerText = "Invalid Password"; but.style.marginTop = "20px"; } if (nm > 0 && pwd > 0) { window.location.replace("main.html"); } nm = 0; pwd = 0; } // 页面加载完成后绑定事件 document.addEventListener('DOMContentLoaded', () => { document.getElementById("username").addEventListener('change', incre); document.getElementById("pwd").addEventListener('change', incre); document.getElementById("but").addEventListener('click', comp); });
同时修改login.html,移除标签内的事件属性:
<input type="text" id="username" placeholder="User-Name"><br> <span id="usernameerr"></span><br> <input type="password" id="pwd" placeholder="Password"><br> <span id="passworderr"></span><br> <button id="but">Login</button>
步骤3:修复数据库连接的错误方式
浏览器无法直接连接MySQL,必须通过后端接口中转:
- 用Node.js + Express写后端接口:
// server.js const express = require('express'); const mysql = require('mysql2/promise'); const app = express(); const port = 3000; // 允许跨域请求 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET'); next(); }); // 提供用户列表接口 app.get('/api/login-users', async (req, res) => { try { const pool = mysql.createPool({ host: "localhost", user: "root", password: "root123", database: "vishnu" }); const [rows] = await pool.query("select * from login"); res.json(rows); } catch (err) { console.error(err); res.status(500).json({ error: 'Failed to fetch users' }); } }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
- 前端login.js改用fetch获取数据:
let rows = []; let nm = 0; let pwd = 0; // 从后端接口获取用户数据 async function fetchUsers() { try { const response = await fetch('http://localhost:3000/api/login-users'); rows = await response.json(); console.log(rows); } catch (err) { console.error('Failed to fetch users:', err); } } // ... 保留incre、comp函数不变 // 页面加载时获取数据并绑定事件 document.addEventListener('DOMContentLoaded', async () => { await fetchUsers(); document.getElementById("username").addEventListener('change', incre); document.getElementById("pwd").addEventListener('change', incre); document.getElementById("but").addEventListener('click', comp); });
内容的提问来源于stack exchange,提问作者Vishnu Viahnu
相关产品推荐
相关产品推荐

