Render basic HTML view?

2019-01-01 05:57发布

I have a basic node.js app that I am trying to get off the ground using Express framework. I have a views folder where I have an index.html file. But I receive the following error when loading the web browser.

Error: Cannot find module 'html'

Below is my code.

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

What am I missing here?

26条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 06:35

For my project I have created this structure:

index.js
css/
    reset.css
html/
    index.html

This code serves index.html for / requests, and reset.css for /css/reset.css requests. Simple enough, and the best part is that it automatically adds cache headers.

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楼-- · 2019-01-01 06:35

I added below 2 line and it work for me

    app.set('view engine', 'html');
    app.engine('html', require('ejs').renderFile);
查看更多
若你有天会懂
4楼-- · 2019-01-01 06:36

Try res.sendFile() function in Express routes.

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

Read here : http://codeforgeek.com/2015/01/render-html-file-expressjs/

查看更多
素衣白纱
5楼-- · 2019-01-01 06:37

With Express 4.0.0, the only thing you have to do is comment out 2 lines in app.js:

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

And then drop your static file into the /public directory. Example: /public/index.html

查看更多
永恒的永恒
6楼-- · 2019-01-01 06:37

I didn't want to depend on ejs for simply delivering an HTML file, so I simply wrote the tiny renderer myself:

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 );
} );
查看更多
素衣白纱
7楼-- · 2019-01-01 06:38

To render Html page in node try the following,

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

app.engine('html', require('ejs').renderFile);
  • You need to install ejs module through npm like:

       npm install ejs --save
    
查看更多
登录 后发表回答