我有一个基本的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')
我错过了什么?
如果你想渲染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()中,它将工作
如果你试图提供一个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文件,上面是一种非常轻量级的方式。