Node.js中使用DOM修改文本报错:document is not defined
问题解决:ReferenceError: document is not defined
错误原因
你在Express服务器代码里调用了document.querySelector(),但document是浏览器环境特有的DOM对象,Node.js运行在服务器端,根本没有这个对象,所以会报错。服务器的职责是处理请求、返回响应,不能直接操作前端页面的DOM元素——DOM操作必须放在浏览器端的JavaScript代码里完成。
两种解决方案
方案一:传统表单提交(带错误参数重定向)
适合新手快速实现,核心是密码错误时重定向回首页,通过URL参数传递错误状态,再由前端JS读取参数显示提示。
- 修改Node.js代码
import express from "express"; import { dirname } from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const correctPassword = "ILoveProgramming"; app.use(bodyParser.urlencoded({ extended: true })); // 首页路由,接收错误参数 app.get("/", (req, res) => { res.sendFile(__dirname + "/public/index.html"); }); // 密码校验路由 app.post("/check", (req, res) => { const inputPassword = req.body.password; if (inputPassword === correctPassword) { res.sendFile(__dirname + "/public/secret.html"); } else { // 重定向回首页,带上错误标记 res.redirect("/?error=true"); console.log("密码错误"); } }); app.listen(port, () => { console.log(`服务器运行在端口 ${port}`); });
- 修改HTML文件,添加前端JS处理错误提示
<form action="/check" method="POST"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> <script> // 读取URL中的错误参数 const urlParams = new URLSearchParams(window.location.search); if (urlParams.has('error')) { document.querySelector('p').textContent = "incorrect password"; } </script>
方案二:AJAX异步提交(无刷新页面)
用户体验更好,表单提交不刷新页面,直接在当前页显示错误提示。
- 修改HTML文件
<form id="passwordForm"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> <script> const form = document.getElementById('passwordForm'); const errorElement = document.querySelector('p'); // 监听表单提交事件 form.addEventListener('submit', async (e) => { e.preventDefault(); // 阻止默认刷新提交行为 const password = document.getElementById('password').value; // 发送异步请求到服务器 const response = await fetch('/check', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `password=${encodeURIComponent(password)}` }); if (response.ok) { // 密码正确,跳转到秘密页面 window.location.href = '/secret'; } else { // 密码错误,显示提示 errorElement.textContent = "incorrect password"; } }); </script>
- 修改Node.js代码,调整路由逻辑
import express from "express"; import { dirname } from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const correctPassword = "ILoveProgramming"; app.use(bodyParser.urlencoded({ extended: true })); // 首页路由 app.get("/", (req, res) => { res.sendFile(__dirname + "/public/index.html"); }); // 秘密页面路由 app.get("/secret", (req, res) => { res.sendFile(__dirname + "/public/secret.html"); }); // 密码校验路由 app.post("/check", (req, res) => { const inputPassword = req.body.password; if (inputPassword === correctPassword) { res.sendStatus(200); // 返回成功状态码 } else { res.sendStatus(401); // 返回未授权状态码 console.log("密码错误"); } }); app.listen(port, () => { console.log(`服务器运行在端口 ${port}`); });
内容的提问来源于stack exchange,提问作者AbhishekTailor700
相关产品推荐
相关产品推荐

