44

很久没用过Node.js,也没用过express。当我开始我的应用程序时,它刚刚返回:

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)

我启动 test.html 时发生错误。这是代码:

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
4

6 回答 6

68

我假设 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');

这是告诉快递

  • 在视图目录中查找要渲染的文件

  • 使用 mustache 渲染文件

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

于 2013-04-19T18:42:53.263 回答
29

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

app.engine('html', require('ejs').renderFile);
于 2014-06-10T12:26:13.010 回答
9

如果不是,请安装 ejs。

npm install ejs

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

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

app.engine('html', require('ejs').renderFile);
于 2020-06-27T14:42:39.813 回答
3

这就是我为渲染 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 页面将正确呈现。

于 2016-06-13T05:39:15.587 回答
2

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

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

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

或者

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

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

于 2013-04-19T18:43:38.810 回答
2

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

于 2020-12-30T02:41:50.233 回答