本文介绍了nuxt.js-如何在服务器端为所有客户端缓存axios调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a vue + nuxt.js application, I like to know if it is possible to cache an axios webservice call for all clients. I have to get some currency reference data and this makes not much sense that every client has to call this data.

有人可以给我一些提示甚至示例吗?谢谢.

Can someone provide me some hints or even an example? Thx.

推荐答案

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

Here is working solution with latest Nuxt 2.11, using locally defined module.

首先将本地模块添加到nuxt.config.js

First add a local module to nuxt.config.js

modules: [
   "@/modules/axCache",
...
]

然后

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

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

请注意,这对服务器/客户端均适用,并且可以配置为仅在一侧使用.

Note, this works for both server/client sides and can be configured to work only on one side.

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

这篇关于nuxt.js-如何在服务器端为所有客户端缓存axios调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 15:57