我正在构建一个应用程序,我有一个类似于此的路由文件。
const router = require('express').Router();
router.get('/', (req, res) => res.render('statics/home'));
router.get('/jobs', (req, res) => res.render('statics/jobs'));
router.get('/about-page', (req, res) => res.render('statics/about-page'));
router.get('/valves', (req, res) => res.render('statics/valves'));
router.all('*', (req, res) => res.notFound());
module.exports = router;
我试图想出一种重构路由的方法,并且有一条接受任何字符串的路由,然后检查文件是否存在与之匹配
任何帮助表示赞赏!
答案 0 :(得分:0)
这样的事情可行:
const router = require('express').Router();
const fs = require('fs');
router.get(':template', (req, res) => {
const tpl = req.param('template');
if (tpl) {
if (fs.existsSync('/path/to/templates/' + tpl + '.ext')) { // adjust the path and template extension
res.render('statics/' + tpl);
} else {
res.notFound();
}
} else {
res.render('statics/home');
}
});
router.all('*', (req, res) => res.notFound());
module.exports = router;
或者更好的方法是读取模板目录一次并根据其内容创建路径:
const router = require('express').Router();
const fs = require('fs');
const templates = fs.readdirSync('/path/to/templates');
templates.forEach(tpl => {
tpl = tpl.substring(tpl.lastIndexOf('/') + 1);
if (tpl === 'home') {
router.get('/', (req, res) => res.render('statics/home'))
} else {
router.get('/' + tpl, (req, res) => res.render('statics/' + tpl))
}
});
router.all('*', (req, res) => res.notFound());
module.exports = router;
答案 1 :(得分:0)
要轻松处理静态文件,可以使用express static,express会自动将所有文件路由到静态文件夹中
app = require('express')();
app.use('statics',express.static('statics'));