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)
app.get('/', function(req, res) {
res.render('./public/danial/forms/form1.html');
});
[EDIT]
To render static html files use the static middleware:
app.use(express.static(path.join(__dirname, 'public')));
What this does is tell express to look for static files in the public directory of the application.
Finally I myself find my answer.I use ejs
template and change my extension of HTML
files to ejs
and render them and for needed files I use public folder.
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.