使用Express搭建TodoList时index.html无法加载,本地主机显示空白页
问题解决:无法在Express中正确渲染index.html页面
核心问题分析
- 路径解析错误:直接使用
__dirname + "todolist-v1\index.html"时,\在JavaScript中是转义字符,会导致路径解析异常,同时这种写法也不具备跨平台兼容性。 - 重复响应发送:
res.sendFile()执行后会自动结束响应,后续调用res.send()会触发响应已结束的错误;另外res.write()之后应该用res.end()来终止响应,而非res.send()。 - 前端无效引用:index.html里的
<script src="app.js"></script>完全多余,app.js是Node.js后端代码,浏览器无法直接执行。
修正后的app.js
const express = require('express'); const path = require('path'); // 引入path模块安全处理路径 const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()) app.get("/", function (req, res) { let today = new Date(); if (today.getDay() === 0) { res.write("<h1>Yay It's the weekend</h1>"); res.end(); // 用end终止响应,避免重复发送 } else { // 用path.join拼接路径,适配不同操作系统 res.sendFile(path.join(__dirname, 'todolist-v1', 'index.html')); } }); app.listen(3000, function () { console.log(`App listening on port ${3000}`) });
修正后的index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>To Do List</title> </head> <body> <h1>Shit doesnt work!!</h1> <p>What da fuck!?</p> <!-- 移除对后端app.js的无效引用 --> </body> </html>
额外注意事项
- 确认文件目录结构:项目根目录下存在
app.js,且根目录内有todolist-v1文件夹,index.html放在该文件夹中。 - 启动服务前确保已安装express:执行
npm install express。 - 启动服务后访问
http://localhost:3000,非周日时即可看到index.html内容。
内容的提问来源于stack exchange,提问作者Nickless09
相关产品推荐
相关产品推荐

