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

新手上路,请多包涵

当我启动我的应用程序并在我的浏览器中访问 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

原文由 Cxodael 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 505
2 个回答

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

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

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

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

但是,如果您想 渲染 视图,则必须为其使用适当的渲染器。渲染器列表在 consolidate.js 库 中定义。

一旦你决定使用哪个库,就安装它。我使用 mustache 所以这是我的应用程序文件的片段:

 var engines = require('consolidate');

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

这告诉 Express 去——

  • views 目录中查找要渲染的文件
  • 使用 mustache
  • 文件的扩展名是 .html (你也可以使用 .mustache )。

原文由 Akshat Jiwan Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 eagor 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题