问题
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)
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
Example of render static HTML with Node Js Express 4
Dir struct.:
-> root
-> node_modules
-> views
-> index.html
-> app.js
app.js:
var express = require('express');
var app = express();
var path = require("path");
var engines = require('consolidate');
app.use(express.static(path.join(__dirname, 'views')));
app.engine('html', engines.mustache);
app.get('/', function(req, res){
res.render('index.html');
});
app.listen(8080);
来源:https://stackoverflow.com/questions/25270434/nodejs-how-to-render-static-html-with-express-4