我有一个基本的Node.js应用程序,我试图使用Express框架启动。我有一个views文件夹,其中有一个index.html文件。但是我在加载网页时收到以下错误:
Error: Cannot find module 'html'
下面是我的代码。
var express = require('express');
var app = express.createServer();
app.use(express.staticProvider(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8080, '127.0.0.1')
我错过了什么?
这些答案很多都已经过时了。
使用快捷3.0.0和3.1.0,以下工作:
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
请参阅下面的注释,了解表达式3.4+的替代语法和注意事项:
app.set('view engine', 'ejs');
然后你可以这样做:
app.get('/about', function (req, res)
{
res.render('about.html');
});
这里假设views子文件夹中有视图,并且已经安装了ejs节点模块。如果不是,在Node控制台中执行以下命令:
npm install ejs --save
如果你想渲染HTML文件,你可以使用sendFile()方法而不使用任何模板引擎
const express = require("express")
const path = require("path")
const app = express()
app.get("/",(req,res)=>{
res.sendFile(**path.join(__dirname, 'htmlfiles\\index.html')**)
})
app.listen(8000,()=>{
console.log("server is running at Port 8000");
})
我在htmlfile里面有一个HTML文件,所以我使用路径模块来渲染index.html路径是节点中的默认模块。如果你的文件是在根文件夹刚刚使用
res.sendFile(path.join(__dirname, 'htmlfiles\\index.html'))
在app.get()中,它将工作
我在特快3中也遇到了同样的问题。X和节点0.6.16。以上给出的解决方案不适用于最新版本的express 3.x。他们删除了app.register方法,并添加了app.engine方法。如果您尝试上述解决方案,可能会出现以下错误。
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'register'
at Function.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:37:5)
at Function.configure (/home/user1/ArunKumar/firstExpress/node_modules/express/lib/application.js:399:61)
at Object.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:22:5)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)
来消除错误消息。在app.configure函数中添加以下代码行
app.engine('html', require('ejs').renderFile);
注意:你必须安装ejs模板引擎
npm install -g ejs
例子:
app.configure(function(){
.....
// disable layout
app.set("view options", {layout: false});
app.engine('html', require('ejs').renderFile);
....
app.get('/', function(req, res){
res.render("index.html");
});
注意:最简单的解决方案是使用ejs模板作为视图引擎。你可以在*中编写原始HTML。Ejs视图文件。
对于我的项目,我创建了这样的结构:
index.js
css/
reset.css
html/
index.html
这段代码为/请求服务index.html,为/css/reset.css请求服务reset.css。很简单,最好的部分是它自动添加缓存头。
var express = require('express'),
server = express();
server.configure(function () {
server.use('/css', express.static(__dirname + '/css'));
server.use(express.static(__dirname + '/html'));
});
server.listen(1337);