当我启动我的应用程序并在我的浏览器中访问 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 许可协议
我假设
test.html
是一个静态文件。要呈现静态文件,请像这样 使用 静态中间件:这告诉 Express 在应用程序的公共目录中查找静态文件。
指定后,只需将浏览器指向文件的位置,它就会显示出来。
但是,如果您想 渲染 视图,则必须为其使用适当的渲染器。渲染器列表在 consolidate.js 库 中定义。
一旦你决定使用哪个库,就安装它。我使用
mustache
所以这是我的应用程序文件的片段:这告诉 Express 去——
views
目录中查找要渲染的文件mustache
.html
(你也可以使用.mustache
)。