繁体   English   中英

访问 HTML 页面时出现“错误:找不到模块 html”

[英]"Error: Cannot find module html" when visiting HTML page

当我启动我的应用程序并在我的浏览器中访问localhost:8333时,它抛出了一个错误:

Error: Cannot find module 'html'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at new View (C:\Users\fr\node_modules\express\lib\view.js:42:49)
  at Function.app.render (C:\Users\fr\node_modules\express\lib\application.js:483:12)
  at ServerResponse.res.render (C:\Users\fr\node_modules\express\lib\response.js:755:7)
  at allClients (C:\Users\fr\node_modules\apps\chat.js:13:7)
  at callbacks (C:\Users\fr\node_modules\express\lib\router\index.js:161:37)
  at param (C:\Users\fr\node_modules\express\lib\router\index.js:135:11)

这是我的代码:

var io = require('socket.io');
var express = require('express');

var app = express(),
http = require('http'),
server = http.createServer(app),
socket = require('socket.io').listen(server);

app.configure(function(){
    app.use(express.static(__dirname));
});
app.get('/', function(req, res, next){
    res.render('./test.html');
});

server.listen(8333);

这是我的项目文件夹结构:

node_modules/
    express/
    socket.io/
    apps/
        chat.js
        test.html

这是我的新app.configure

app.configure(function(){
    app.use(express.static(path.join(__dirname, 'public')));
});

但是该代码失败并出现此错误:

path is not defined

我假设 test.html 是一个静态文件。要呈现静态文件,请使用像这样的静态中间件。

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

这告诉 express 在应用程序的公共目录中查找静态文件。

指定后,只需将浏览器指向文件的位置,它就会显示出来。

但是,如果你想渲染视图,那么你必须使用适当的渲染器。渲染列表在consolidate 中定义。一旦你决定使用哪个库,就安装它。我使用 mustache 所以这里是我的一个片段配置文件

var engines = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

这样做是告诉 express 到

  • 在视图目录中查找要呈现的文件

  • 使用 mustache 渲染文件

  • 文件的扩展名是 .html(你也可以使用 .mustache)

简单的方法是使用 EJS 模板引擎来提供 .html 文件。 将此行放在您的视图引擎设置旁边:

app.engine('html', require('ejs').renderFile);

如果不是,请安装 ejs。

npm install ejs

然后在您的主文件中粘贴以下两行之后。 (如 app.js、main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

这就是我为渲染 html 文件所做的。 它解决了错误。 通过在项目文件夹中执行以下命令来安装consolidatemustache

$ sudo npm install consolidate mustache --save

并对您的app.js文件进行以下更改

var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

现在 html 页面将正确呈现。

我认为您可能需要声明一个视图引擎。

如果要使用视图/模板引擎:

app.set('view engine', 'ejs');

要么

app.set('view engine', 'jade');

但是要渲染纯 html,请参阅这篇文章: 渲染基本 HTML 视图? .

采用

res.sendFile()

代替

res.render()

您要做的是发送整个文件。

这对我有用。

尝试从 npm 安装html模块:

npm i html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM