我有一个基本的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路由处理,而以前它们是由静态中间件处理的。这将允许我渲染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');       
        });

结果很好。

其他回答

来自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

我试图用一个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)
});

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

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

表达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