0

我有这些视图渲染调用:

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

  }

是这样吗?我想我错过了一些标题?没有人知道正确的标题是什么?

4

1 回答 1

1

我不确定您对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);
于 2020-04-02T01:32:36.633 回答