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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With