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

我错过了什么?


当前回答

向代码中添加以下行

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

欢呼:)

其他回答

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

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

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

在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

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

如果你使用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”);