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

我错过了什么?


当前回答

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

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

其他回答

我试图用一个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页面,请尝试以下操作,

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

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

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

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

试试这个。这对我很管用。

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

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