nuxt.js - 如何在服务器端为所有客户端缓存 axios 调用

meg*_*off 5 caching vue.js axios nuxt.js

我正在使用 vue + nuxt.js 应用程序,我想知道是否可以为所有客户端缓存 axios webservice 调用。我必须获得一些货币参考数据,这对于每个客户都必须调用这些数据没有多大意义。

有人可以给我一些提示,甚至是一个例子吗?谢谢。

小智 7

这是最新 Nuxt 2.11 的工作解决方案,使用本地定义的模块。

首先在nuxt.config.js中添加一个本地模块

modules: [
   "@/modules/axCache",
...
]
Run Code Online (Sandbox Code Playgroud)

然后

//  modules/axCache.js
import LRU from "lru-cache"

export default function(_moduleOptions) {
  const ONE_HOUR = 1000 * 60 * 60
  const axCache = new LRU({ maxAge: ONE_HOUR })

  this.nuxt.hook("vue-renderer:ssr:prepareContext", ssrContext => {
    ssrContext.$axCache = axCache
  })
}
Run Code Online (Sandbox Code Playgroud)

// plugins/axios.js
import { cacheAdapterEnhancer } from "axios-extensions"
import LRU from "lru-cache"
const ONE_HOUR = 1000 * 60 * 60

export default function({ $axios, ssrContext }) {
  const defaultCache = process.server
    ? ssrContext.$axCache
    : new LRU({ maxAge: ONE_HOUR })

  const defaults = $axios.defaults
  // https://github.com/kuitos/axios-extensions
  defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
    enabledByDefault: false,
    cacheFlag: "useCache",
    defaultCache
  })
}
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于服务器/客户端,并且可以配置为仅在一侧工作。

解决方案:https : //github.com/nuxt-community/axios-module/issues/99