【问题标题】:Node Cache-Control - unable to set headers in client/build节点缓存控制 - 无法在客户端/构建中设置标头
【发布时间】:2021-06-11 21:58:30
【问题描述】:

我正在使用带有 node/express 的 create react 应用程序。我正在尝试解决 Lighthouse 报告的性能问题“使用有效的缓存策略提供静态资产”。

我尝试过以多种方式设置 Cache-Control。以下是当前配置,但它不起作用。

let options = {
      etag: true,
      maxAge: 31536000,
      redirect: true,
      setHeaders: function (res, path, stat) {
        res.set(
          {
          'x-timestamp': Date.now(),
          'robert': 'hi'
          }
        )
      }
    };

let indexOptions = {
  'Cache-Control': 'no-cache'
};

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  // app.use(express.static(path.join(__dirname, 'client/build')));
  // ADDED OPTIONS WITH CACHE EXPIRY
  app.use(express.static(path.join(__dirname, 'client/build'), options));
  // app.use(express.static(path.join(__dirname, 'client/build'), {'Cache-Control': 'client/build, max-age=31536000'}));
  // Handle React routing, return all requests to React app
  app.get('*', function (req, res) {
    // res.sendFile(path.join(__dirname, 'client/build', 'index.html'), {'Cache-Control': 'no-cache'});
    // res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'), indexOptions);
  });
}

我没有收到任何错误,只是没有在索引或其他文件上设置任何错误。

【问题讨论】:

    标签: node.js webpack create-react-app cache-control


    【解决方案1】:

    我会检查您是否在部署中将 NODE_ENV 设置为生产环境,方法是在部署代码时禁用环境检查或控制台记录环境变量。对于它的价值,我通常会检查NODE_ENV !== 'development',而不是出于几个原因检查生产。许多构建管道,例如 create-react-app,会在构建代码时剥离 dev only 代码。此外,NODE_ENV = 'production' 不一定在生产环境中设置,因此您必须确保部署的任何内容都可以设置它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      相关资源
      最近更新 更多