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

我错过了什么?


当前回答


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"] );                                
};);

其他回答

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

使用快捷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()中,它将工作

index.js

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));


app.get('/', function(req, res) {
    res.render('index.html');
});


app.listen(3400, () => {
    console.log('Server is running at port 3400');
})

将index.html文件放到公共文件夹中

<!DOCTYPE html>
<html>
<head>
    <title>Render index html file</title>
</head>
<body>
    <h1> I am from public/index.html </h1>
</body>
</html>

现在在终端上运行以下代码

节点index.js


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"] );                                
};);

如果您不需要使用views目录,只需将html文件移动到下面的公共目录即可。

然后,将这一行添加到app.configure中,而不是'/views'。

server.use(express.static(__dirname + '/public'));