如何缓存视图,以便不需要重新读取和重新呈现文件



我有以下视图渲染调用:

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()和所有内容做了什么,但您可以使用带有max-age值的Cache-Control标头来告诉浏览器缓存您发送的任何内容:

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);

相关内容

  • 没有找到相关文章

最新更新