node.js - Gatsby 中的缓存破坏 page-data.json 文件

标签 node.js browser-cache gatsby

我有一个 gatsby 生成的网站,我已经在其中替换了主页的内容。

不幸的是,以前的版本正在提供/page-data/index/page-data.json使用不正确的缓存控制 header ,导致 /page-data/index/page-data.json缓存在客户端浏览器上(除非强制刷新,否则会显示陈旧数据)。我还发现 page-data.json 文件没有经过哈希处理(请参阅 https://github.com/gatsbyjs/gatsby/issues/15080 )。

我已经更新了缓存控制 header ,以便从现在开始的版本不会被缓存,但这对现在拥有缓存版本的客户端没有帮助。

我该怎么做才能强制客户端请求此文件的最新版本?

最佳答案

我终于到了那里...这是我的 gatsby-node.js

const hash = md5(`${new Date().getTime()}`)

const addPageDataVersion = async file => {
  const stats = await util.promisify(fs.stat)(file)
  if (stats.isFile()) {
    console.log(`Adding version to page-data.json in ${file}..`)
    let content = await util.promisify(fs.readFile)(file, 'utf8')
    const result = content.replace(
      /page-data.json(\?v=[a-f0-9]{32})?/g,
      `page-data.json?v=${hash}`
    )
    await util.promisify(fs.writeFile)(file, result, 'utf8')
  }
}

exports.onPostBootstrap = async () => {
  const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js')
  await addPageDataVersion(loader)
}

exports.onPostBuild = async () => {
  const publicPath = path.join(__dirname, 'public')
  const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`)
  for (let file of htmlAndJSFiles) {
    await addPageDataVersion(file)
  }
}

关于node.js - Gatsby 中的缓存破坏 page-data.json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223669/

相关文章:

html - 防止 google chrome 缓存 html 页面

android - 是否可以从 webview 缓存中保存/检索特定数据?

javascript - 仅在生产环境中使用 Gatsby 和 Material UI 时,首次访问页面时 HTML 消失

node.js - Express 中中间件测试的 stub 请求\响应

javascript - Jade.js 与 jQuery

node.js - 如何在 WebStorm 中调试 React Express Webpack 应用程序

c++ - 如何阻止 Curl 缓存数据

javascript - 从 Electron 应用程序打印

reactjs - 在《 Gatsby 》中将 Prop 从布局传递给 child

reactjs - GraphQL 查询适用于 Gatsby 页面,但不适用于类组件