You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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>

额外注意事项

  1. 确认文件目录结构:项目根目录下存在app.js,且根目录内有todolist-v1文件夹,index.html放在该文件夹中。
  2. 启动服务前确保已安装express:执行npm install express。
  3. 启动服务后访问http://localhost:3000,非周日时即可看到index.html内容。

内容的提问来源于stack exchange,提问作者Nickless09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:57:54