2

I have a Node Server with Express. I get the cannot find module 'html' error even though my code looks like this and should be correct in my opinion:

app.set('views', path.join(__dirname, 'build/views'));
app.use(favicon(path.join(__dirname, "build/favicon.ico")));
app.use('/scripts', express.static(path.join(__dirname, 'node_modules')));
app.use(express.static(path.join(__dirname, 'build')));

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

3 Answers3

3

You have to set engine for HTML

Include this code in your main file

var engines = require('consolidate');

app.engine('html', engines.mustache);
app.set('view engine', 'html');
abdulbarik
  • 6,101
  • 5
  • 38
  • 59
  • I just quickly changed it to: `res.sendFile(path.join(__dirname + '/build/views/index.html'));` Would this be a nice solution as well or is your solution better/ nicer? –  Sep 15 '16 at 09:13
  • It depends on writing of code structure. Mostly we prefer 'views' to get 'static' pages – abdulbarik Sep 15 '16 at 09:57
  • Yes if you are using Angular then it can't work since angular work on client site and doesn't work on server side – abdulbarik Sep 15 '16 at 10:16
  • What do you mean? I am using NodeJS as a Server and then for the frontEnd I use HTML + AngularJS + CSS + Javascript. And it worked before as well. Before I just had view engine = jade. Should not be a big difference? –  Sep 15 '16 at 10:19
  • The problem is when you use mustache you can pass variables which are recognised by {{}}. AngularJS also does that, but somehow mustache has a higher priority which results in empty variables. A solution would be to change the startSymbol to [[ and end Symbol to ]] for AngularJS –  Sep 15 '16 at 10:31
2

If you only want to serve a static file without passing any variables from the server to the client the easiest solution would be:

res.sendFile(path.join(__dirname + '/build/views/index.html'));

Especially when you are using AngularJS for the client side. The problem with the solution above is that mustache uses {{}} as variables recognition. So does AngularJS which might causes errors!

0

It seems that you are trying to display a static index.html file but you serve it as if it was a template. Probably Express is trying to find a module for html template format, which doesn't exist.

You may try to send the index as a static file instead of with res.render which is for rendering templates.

Some time ago I wrote an example of serving static files with Express. It's available on GitHub:

See also my other answer, where I explain it in more detail.

rsp
  • 107,747
  • 29
  • 201
  • 177