NodeJS, how to render static HTML with Express 4?

五迷三道 提交于 2019-12-10 13:53:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!