Node.js v18.12.1中requrie未定义的ReferenceError问题求助
问题解决
1. 修复致命拼写错误
错误提示ReferenceError: requrie is not defined的核心原因是你把require拼写成了requrie,将代码里的requrie修正为require即可解决这个报错。
2. 修复sendFile路径潜在问题
直接使用res.sendFile("index.html")可能会因Node.js的工作目录与文件实际位置不一致导致找不到文件,建议使用绝对路径,需要引入path模块来拼接路径:
修改后的完整代码:
const express = require("express"); const path = require("path"); // 引入path模块 const app = express(); const port = 3000; app.get("/", function (req, res) { // 使用__dirname拼接index.html的绝对路径,确保文件能被正确找到 res.sendFile(path.join(__dirname, "index.html")); }); app.listen(port, function () { console.log(`Server is running on http://localhost:${port}`); });
验证步骤
- 保存修改后的代码
- 在终端重新执行
node app.js - 访问
http://localhost:3000即可看到index.html的内容
内容的提问来源于stack exchange,提问作者Harshad Tekwani
相关产品推荐
相关产品推荐

