What is the best practice for serving html in node.js with express.js?

二次信任 提交于 2019-11-28 17:30:51

You could use the static middleware:

app.use("/", express.static(__dirname));

A server example:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});

This is the file structure:

.
├── public
│   ├── a.html
│   ├── b.html
│   └── c.html
└── server.js

Documentation:

One idea would be to use a catch-all kind of route as the last route, like the following:

app.get('/:page', function(req, res) {
  res.sendfile(path.join(__dirname, 'public', 'pages', path.basename(req.params.page) + '.html'));
});

That would require that you put your .html files into public/pages/about.html, etc.

You might want to switch the order of the static file router so that static files get precedence over routes, too, unless you want that route catching things in the public folder, like this:

app

app.set('view engine', 'ejs');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!