我有这些视图渲染调用:
router.get('/mcn', (req, res) => {
res.render('product/mcn', { layout: 'product/layout', contactKey: 'mcn' });
});
router.get('/agency', (req, res) => {
res.render('product/agency', { layout: 'product/layout', contactKey: 'agency' });
});
router.get('/esports', (req, res) => {
res.render('product/esports', { layout: 'product/layout', contactKey: 'esports' });
});
router.get('/brand', (req, res) => {
res.render('product/brand', { layout: 'product/layout', contactKey: 'brand' });
});
router.get('/analytics', (req, res) => {
res.render('product/analytics', { layout: 'product/layout', contactKey: 'analytics' });
});
router.get('/rightsmanagement', (req, res) => {
res.render('product/content-id', { layout: 'product/layout', contactKey: 'content-id' });
});
您可能会注意到-没有传递动态数据。所以我想知道如何缓存这些视图?像这样的东西:
const pug = require('pug');
{
const templateStr = fs.readFileSync(path.resolve(__dirname +'/../views/product/content-id'));
const fn = pug.compile(templateStr, {});
const html = fn({ layout: 'product/layout', contactKey: 'content-id' });
router.get('/rightsmanagement', (req, res) => {
res.send(html);
});
}
那是对的吗?我想我缺少一些标题了吗?没人知道正确的标题是什么吗?
我不确定您对pug.compile()
以及所有内容的处理方式,但是您可以将Cache-Control
标头与max-age
值一起使用,以告诉浏览器缓存您发送的所有内容:
router.get('/rightsmanagement', (req, res) => {
// set max-age to whatever you think is best
res.set('Cache-Control', 'max-age=31536000');
res.send(html);
});
您可能会使用它作为中间件来设置渲染,因为req.path
包括处理程序中唯一的动态内容,但rightsmanagment
路由的特殊情况除外:
const renderCacheView = (req, res, next) => {
let path = req.path;
if (path === 'rightsmanagement') path = 'content-id';
// set max-age to whatever you think is best
res.set('Cache-Control', 'max-age=31536000');
res.render(`product/${path}`, { layout: 'product/layout', contactKey: path});
};
我认为您甚至可以利用传递正则表达式作为路径这一事实,而不必写太多的路线,而无需这样做:
router.get(/mcn|agency|esports|brand|analytics|rightsmanagement/, renderCacheView);