Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS, how to render static HTML with Express 4?

I need to render HTML files in express 4, I write something like this but not works good.

  app.route('/form1').get(function(req,res){
        res.sendfile('./public/danial/forms/form1.html');
  });

This code can send the HTML file ,but it exactly send the HTML file and don't send css or js files that HTML file need them ,this is the logs :

   GET /form1 304 2.743 ms - -
   GET /css/bootstrap.css 404 2.284 ms - -
   GET /css/bootstrap-theme.css 404 2.193 ms - -
   GET /css/bootstrap-switch.css 404 2.226 ms - -
   // and many others

I need to do something like this:

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

how can I fix it?

(many other questions are for express 3 and I can't find answer)

like image 733
Elyas74 Avatar asked Aug 12 '14 17:08

Elyas74


1 Answers

Render HTML in Express 4 without a View Engine

take the following directory structure for example..

-> root
   -> node_modules
      -> express
      -> html
   -> public
      -> pages
         -> index.html
   -> app.js

app.js

var express = require('express');
var app     = express();
var path    = require("path");

// set static directories
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname+ '/public/pages/index.html'));
});

var port = process.env.PORT || 5000;
app.listen(port);
console.log('Listening on port ',  port);

Note: If you get this error.. Cannot find module 'html' Its because you are missing the HTML node module. Run npm install html command from your project root to fix this issue.

like image 121
Kris Hollenbeck Avatar answered Dec 25 '22 03:12

Kris Hollenbeck