简体   繁体   中英

Nodejs: Error: Cannot find module 'html'

im using nodejs and im trying to serve only html files (no jade, ejs ... engines).

heres my entry point (index.js) code:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

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

app.get('*', function(req, res){
    res.render('index.html');
});

app.listen(app.get('port'), function() {
});

This is doing just fine when i hit the url "localhost:5000/", but when i try something like "localhost:5000/whatever" i got the following message: Error: Cannot find module 'html'

im new to nodejs, but i want all routes to render the index.html file. How can i do that ???

Thank you.

You need to specify your view folder and parse the engine to HTML.

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());



app.get('*', function(req, res){
    res.render('index.html');
});

app.listen(app.get('port'), function() {
});

Use render only when using a rendering engines like jade or ejs. If you want to use plain HTML, place it in the public folder or serve it as a static file.

res.sendFile('index2.html', {root : __dirname + '/views'});

First of all you need to install ejs engine. For that you can use the following code

npm install ejs

After that you need to add app engine and set the view directory.

The changed code is given below,

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.listen(app.get('port'), function() {
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM