我有一个基本的 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 页面:
在意见/index.jade
include plain.html
在视图/plain.html
<!DOCTYPE html>
...
并且 app.js 仍然可以只渲染玉:
res.render(index)
其中许多答案已经过时。
使用 express 3.0.0 和 3.1.0,以下工作:
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
有关 express 3.4+ 的替代语法和注意事项,请参阅下面的评论:
app.set('view engine', 'ejs');
然后您可以执行以下操作:
app.get('/about', function (req, res)
{
res.render('about.html');
});
这假设您在 views
子文件夹中有您的视图,并且您已经安装了 ejs
节点模块。如果没有,请在节点控制台上运行以下命令:
npm install ejs --save
来自 Express.js 指南:View Rendering
查看文件名采用 Express.ENGINE 的形式,其中 ENGINE 是所需模块的名称。例如视图 layout.ejs 会告诉视图系统 require('ejs'),被加载的模块必须导出方法exports.render(str, options) 以符合Express,但是可以使用app.register()将引擎映射到文件扩展名,以便例如 foo.html 可以由jade呈现。
因此,要么创建自己的简单渲染器,要么只使用翡翠:
app.register('.html', require('jade'));
More 关于 app.register
。
请注意,在 Express 3 中,此方法被重命名为 app.engine
app.engine('.html', require('ejs').renderFile);
您还可以阅读 HTML 文件并将其发送:
app.get('/', (req, res) => {
fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
res.send(text);
});
});
尝试这个。这个对我有用。
app.configure(function(){
.....
// disable layout
app.set("view options", {layout: false});
// make a custom html template
app.register('.html', {
compile: function(str, options){
return function(locals){
return str;
};
}
});
});
....
app.get('/', function(req, res){
res.render("index.html");
});
app.register
上看到一个错误。也许它在 express 3.0.0.rc3 中已被弃用? TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'register'
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
如果您使用的是 express@~3.0.0,请从您的示例中更改以下行:
app.use(express.staticProvider(__dirname + '/public'));
像这样:
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
我按照 express api page 中的描述制作了它,它就像魅力一样。使用该设置,您不必编写额外的代码,因此它可以很容易地用于您的微生产或测试。
完整代码如下:
var express = require('express');
var app = express.createServer();
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8080, '127.0.0.1')
app.listen
启动服务器后重复 app.use(express.static(__dirname + '/public'));
?
我在 express 3.X
和 node 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 function
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 模板作为视图引擎。在那里,您可以在 *.ejs 视图文件中编写原始 HTML。
ejs
?
文件夹结构:
.
├── index.html
├── node_modules
│ ├──{...}
└── server.js
服务器.js
var express = require('express');
var app = express();
app.use(express.static('./'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8882, '127.0.0.1')
索引.html
<!DOCTYPE html>
<html>
<body>
<div> hello world </div>
</body>
</html>
输出:
你好世界
如果您不必使用views 目录,只需将html 文件移动到下面的公共目录即可。
然后,将此行添加到 app.configure 而不是“/views”中。
server.use(express.static(__dirname + '/public'));
如果你想渲染 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
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);
server.configure
已弃用,因此直接使用 server.use
要在节点中呈现 Html 页面,请尝试以下操作,
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
您需要通过 npm 安装 ejs 模块,例如: npm install ejs --save
使用 Express 4.0.0,您唯一需要做的就是在 app.js 中注释掉 2 行:
/* app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); */ //or whatever the templating engine is.
然后将您的静态文件放入 /public 目录。示例:/public/index.html
快递 4.x
res.sendFile(路径 [, 选项] [, fn])
发送 .html 文件,没有模板引擎...
//...
// Node modules
const path = require('path')
//...
// Set path to views directory
app.set('views', path.join(__dirname, 'views'))
/**
* App routes
*/
app.get('/', (req, res) => {
res.sendFile('index.html', { root: app.get('views') })
})
//...
.
├── node_modules
│
├── views
│ ├──index.html
└── app.js
var app = express(); app.set('views', path.join(__dirname, '../views'));
。如果没有“../folderName”,它会在路由文件夹中查找。
我在 2 行以下添加,它对我有用
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
npm install ejs --save
。
在 Express 路由中尝试 res.sendFile() 函数。
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
//__dirname : It will resolve to your project folder.
});
app.get('/about',function(req,res){
res.sendFile(path.join(__dirname+'/about.html'));
});
app.get('/sitemap',function(req,res){
res.sendFile(path.join(__dirname+'/sitemap.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
在这里阅读:http://codeforgeek.com/2015/01/render-html-file-expressjs/
我不想依赖 ejs 来简单地传递 HTML 文件,所以我只是自己编写了微型渲染器:
const Promise = require( "bluebird" );
const fs = Promise.promisifyAll( require( "fs" ) );
app.set( "view engine", "html" );
app.engine( ".html", ( filename, request, done ) => {
fs.readFileAsync( filename, "utf-8" )
.then( html => done( null, html ) )
.catch( done );
} );
1)最好的方法是设置静态文件夹。在您的主文件(app.js | server.js | ???)中:
app.use(express.static(path.join(__dirname, 'public')));
public/css/form.html public/css/style.css
然后你从“公共”文件夹中得到静态文件:
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"] );
};);
我试图用一个快速的 RESTful API 设置一个有角度的应用程序,并多次登陆这个页面,尽管它没有帮助。这是我发现有效的方法:
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // pull information from html in POST
app.use(express.methodOverride()); // simulate DELETE and PUT
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});
然后在您的 api 路由的回调中如下所示:res.jsonp(users);
您的客户端框架可以处理路由。 Express 用于提供 API。
我的家乡路线如下所示:
app.get('/*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
res.sendFile(__dirname + '/public/login.html');
将以下行添加到您的代码中
在 package.json 文件 "dependencies": { "ejs": "*" } 中用 "ejs" 和 "XYZ"(version) 替换 "jade": { "ejs": "*" } 然后在你的 app.js 文件中添加以下代码: engine('html', require('ejs').renderFile); app.set('视图引擎', 'html');并记住将所有 .HTML 文件保存在视图文件夹中
干杯:)
这是快递服务器的完整文件演示!
https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906
希望对你有帮助!
// HTML 页面的简单快速服务器! // ES6 风格 const express = require('express');常量 fs = 要求('fs');常量主机名 = '127.0.0.1';常量端口 = 3000;常量应用程序 = 快递(); let cache = [];// 数组没问题!缓存[0] = fs.readFileSync(__dirname + '/index.html');缓存[1] = fs.readFileSync(__dirname + '/views/testview.html'); app.get('/', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[0] ); }); app.get('/test', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[1] ); }); app.listen(port, () => { console.log(` 服务器运行在 http://${hostname}:${port}/ 服务器主机名 ${hostname} 正在监听端口 ${port}!` ); });
很遗憾,快到 2020 年了,express 还没有添加不使用 response
对象的 sendFile
方法来呈现 HTML 页面的方法。使用 sendFile
不是问题,但以 path.join(__dirname, 'relative/path/to/file')
的形式向它传递参数感觉不对。为什么用户应该将 __dirname
加入文件路径?它应该默认完成。为什么服务器的根目录不能默认为项目目录?此外,安装模板依赖项只是为了呈现静态 HTML 文件也是不正确的。我不知道解决该问题的正确方法,但如果我必须提供静态 HTML,那么我会执行以下操作:
const PORT = 8154;
const express = require('express');
const app = express();
app.use(express.static('views'));
app.listen(PORT, () => {
console.log(`Server is listening at port http://localhost:${PORT}`);
});
上面的示例假定项目结构有一个 views
目录,并且静态 HTML 文件位于其中。例如,假设 views
目录有两个名为 index.html
和 about.html
的 HTML 文件,那么要访问它们,我们可以访问:localhost:8153/index.html
或只访问 localhost:8153/
来加载 index.html
页面和 { 8} 加载about.html
。我们可以通过将工件存储在 views
目录中或仅使用默认 dist/<project-name>
目录并在服务器 js 中配置它来使用类似的方法来提供 react/angular 应用程序,如下所示:
app.use(express.static('dist/<project-name>'));
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>
现在在您的终端中运行以下代码
节点索引.js
对于纯 html,您不需要任何 npm 包或中间件
就用这个:
app.get('/', function(req, res) {
res.sendFile('index.html');
});
我想允许对“/”的请求由 Express 路由处理,而之前它们由静态中间件处理。这将允许我渲染 index.html 的常规版本或加载连接 + 缩小 JS 和 CSS 的版本,具体取决于应用程序设置。受 Andrew Homeyer's answer 的启发,我决定将我的 HTML 文件(未经修改)拖到视图文件夹中,像这样配置 Express
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
并像这样创建了一个路由处理程序
app.route('/')
.get(function(req, res){
if(config.useConcatendatedFiles){
return res.render('index-dist');
}
res.render('index');
});
这效果很好。
在 server.js 中,请包含
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
//__dirname : It will resolve to your project folder.
});
如果您尝试提供一个已经包含所有内容的 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 文件,那么上面是一种非常轻量级的方式。
我通常用这个
app.configure(function() {
app.use(express.static(__dirname + '/web'));
});
请小心,因为这将共享 /web 目录中的任何内容。
我希望它有帮助
不定期副业成功案例分享