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

我错过了什么?


来自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文件并发送它:

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.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});

你可以让jade包含一个普通的HTML页面:

在视图/ index.jade

include plain.html

在视图/ plain.html

<!DOCTYPE html>
...

而app.js仍然可以渲染jade:

res.render(index)

对于我的项目,我创建了这样的结构:

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);

我在特快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视图文件。

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

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

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

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

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

如果你使用express@~3.0.0修改下面的代码行:

app.use(express.staticProvider(__dirname + '/public'));

就像这样:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

我做了它的描述在express api页面,它的工作就像魅力。有了这样的设置,你就不需要编写额外的代码,所以它很容易用于你的微产品或测试。

完整代码如下所示:

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.configure(function() {
    app.use(express.static(__dirname + '/web'));
});

只是要小心,因为它会共享/web目录中的任何内容。

我希望这对你们有帮助

如果你使用express framework到node.js

安装 npm EJS

然后添加配置文件

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router)

;

从exports模块form.js中呈现页面 HTML文件在视图目录 扩展ejs文件名称为 form.html.ejs

然后创建form.js

res.render(“form.html.ejs”);


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

我试图用一个RESTful API创建一个angular应用,并多次登陆这个页面,尽管它并没有什么帮助。以下是我发现有效的方法:

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

在Express 4.0.0中,你唯一要做的就是注释掉app.js中的两行:

/* app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); */ //or whatever the templating engine is.

然后将静态文件放到/public目录中。例如:/公共/ index . html

我想允许对“/”的请求由Express路由处理,而以前它们是由静态中间件处理的。这将允许我渲染index.html的常规版本或加载连接+最小化JS和CSS的版本,这取决于应用程序设置。受到Andrew Homeyer回答的启发,我决定将我的HTML文件(未修改)拖到views文件夹中,并像这样配置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');       
        });

结果很好。

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

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

尝试Express routes中的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/

res.sendFile(__dirname + '/public/login.html');

在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.
});

向代码中添加以下行

将“jade”替换为“ejs”,“X.Y.Z”(版本)替换为“*”。json文件 “依赖”:{ “ejs”:“*” } 然后在app.js文件中添加以下代码: app.engine(“html”,要求(“ejs”).renderFile); App.set('视图引擎','html'); 记住把所有的。html文件保存在views Folder中

欢呼:)

我不想依赖于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 );
} );

要在节点中呈现Html页面,请尝试以下操作,

app.set('views', __dirname + '/views');

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

你需要像这样通过npm安装ejs模块: NPM安装ejs—保存

这里是一个完整的文件演示的express服务器!

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

希望对你有所帮助!

// simple express server for HTML pages! // ES6 style const express = require('express'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 3000; const app = express(); let cache = [];// Array is OK! cache[0] = fs.readFileSync( __dirname + '/index.html'); cache[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(` Server is running at http://${hostname}:${port}/ Server hostname ${hostname} is listening on port ${port}! `); });

文件夹结构:

.
├── index.html
├── node_modules
│   ├──{...}
└── server.js

server.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')

index . html

<!DOCTYPE html>
<html>
<body>

<div> hello world </div>

</body>
</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文件,上面是一种非常轻量级的方式。

对于纯html,你不需要任何npm包或中间件

就用这个吧:

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

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

It is very sad that it is about 2020 still express hasn't added a way to render an HTML page without using sendFile method of the response object. Using sendFile is not a problem but passing argument to it in the form of path.join(__dirname, 'relative/path/to/file') doesn't feel right. Why should a user join __dirname to the file path? It should be done by default. Why can't the root of the server be by defalut the project directory? Also, installing a templating dependency just to render a static HTML file is again not correct. I don't know the correct way to tackle the issue, but if I had to serve a static HTML, then I would do something like:

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}`);
});

The above example assumes that the project structure has a views directory and the static HTML files are inside it. For example, let's say, the views directory has two HTML files named index.html and about.html, then to access them, we can visit: localhost:8153/index.html or just localhost:8153/ to load the index.html page and localhost:8153/about.html to load the about.html. We can use a similar approach to serve a react/angular app by storing the artifacts in the views directory or just using the default dist/<project-name> directory and configure it in the server js as follows:

app.use(express.static('dist/<project-name>'));

表达4.倍

res.sendFile(path [, options] [, 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

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