我有一个基本的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')

我错过了什么?


当前回答

我添加以下2行,它为我工作

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

其他回答

来自Express.js指南:视图渲染

视图文件名采用Express形式。ENGINE,其中ENGINE是所需模块的名称。例如视图布局。Ejs会告诉视图系统require(' Ejs '),被加载的模块必须导出方法exports。render(str, options)来遵守Express,但是app.register()可以用来将引擎映射到文件扩展名,因此,例如foo.html可以由jade渲染。

所以你要么创建自己的简单渲染器,要么使用jade:

 app.register('.html', require('jade'));

更多关于app.register的信息。

注意,在Express 3中,这个方法被重命名为app.engine

如果你想渲染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()中,它将工作


1) 最好的办法是设置静态文件夹。在你的主文件(app.js | server.js | ??):

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

公共/ css / form . html public / css / style . css

然后你从“public”文件夹中获得静态文件:

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

您可以创建您的文件缓存。 使用方法fs.readFileSync

var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');

app.get('/', function(req, res){    
    res.setHeader('Content-Type', 'text/html');
    res.send( cache["index.html"] );                                
};);

如果你试图提供一个HTML文件,其中已经有它所有的内容在里面,那么它不需要被“渲染”,它只需要被“服务”。呈现是指在页面发送到浏览器之前让服务器更新或注入内容,并且它需要额外的依赖项,如ejs,如其他答案所示。

如果你只是想让浏览器根据他们的请求指向一个文件,你应该像这样使用res.sendFile():

const express = require('express');
const app = express();
var port = process.env.PORT || 3000; //Whichever port you want to run on
app.use(express.static('./folder_with_html')); //This ensures local references to cs and js files work

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/folder_with_html/index.html');
});

app.listen(port, () => console.log("lifted app; listening on port " + port));

这样,除了express,您就不需要其他依赖项了。如果你只是想让服务器发送你已经创建的html文件,上面是一种非常轻量级的方式。

这些答案很多都已经过时了。

使用快捷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