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

运行Node.js Express服务器时出现Error: Cannot find module 'html'错误怎么办?

问题解决:Error: Cannot find module 'HTML'

错误原因

你的代码里app.set("view engine", html);这一行存在两个问题:

  • html没有用引号包裹,被Node.js当作变量处理,导致它尝试寻找名为html的模块,从而抛出找不到模块的错误。
  • Express默认不支持直接将HTML作为模板引擎,即使给html加上引号,也需要额外配置才能使用res.render渲染HTML文件。

另外,主页能正常访问大概率是因为express.static中间件优先处理了请求,直接返回了public目录下的index.html,而没有走到app.get('/')的路由逻辑。

解决方案

方案一:使用静态文件服务(推荐纯HTML应用)

这种方式更简单,不需要模板引擎配置:

  1. 删除app.set("view engine", html);这一行。
  2. 将路由里的res.render替换为res.sendFile,指定文件的绝对路径:
const path = require('path');
const port = 8080;
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
})

app.get('/map/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'map.html'));
})

var server = app.listen(8080, function () {
    console.log(`App listening at http://localhost:${server.address().port}/`)
 })
  1. 确保index.html和map.html都放在public目录下,甚至可以直接删除这两个路由,express.static会自动处理静态文件请求(比如直接访问localhost:8080会返回index.html,访问localhost:8080/map.html会返回对应文件)。

方案二:配置HTML模板引擎(适合需要模板渲染的场景)

如果需要使用模板语法,可以借助ejs来渲染HTML:

  1. 安装ejs依赖:
npm install ejs
  1. 修改模板引擎配置:
const path = require('path');
const port = 8080;
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, 'public')));
// 配置html模板引擎,使用ejs的renderFile方法
app.engine('html', require('ejs').renderFile);
app.set("view engine", 'html');
// 指定视图文件目录(如果你的html文件在public里)
app.set('views', path.join(__dirname, 'public'));

app.get('/', (req, res) => {
    res.render('index.html')
})

app.get('/map/', (req, res) => {
    res.render('map.html')
})

var server = app.listen(8080, function () {
    console.log(`App listening at http://localhost:${server.address().port}/`)
 })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:42:23