Nodejs: Error: cannot find module 'html'

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

heres my entry point code (index.js):

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 great when I click on the localhost: 5000 / whatever url, but when I try something like localhost: 5000 / whatever, I get the following message: Error: Cannot find module 'html'

im new for nodejs, but I want all routes to display the index.html file. How can i do this?

Thanks.

+13
source share
3 answers

You need to specify the view folder and analyze the engine in 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() { }); 
+29
source

You can use rendering only when using some rendering engines, such as jade or ejs, if you plan to use simple HTML, put it in a shared folder or serve as a static file.

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

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

 npm install ejs 

After that, you need to add the application engine and set the viewing directory.

The modified code is 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() { }); 
+3
source

Source: https://habr.com/ru/post/977831/


All Articles