本文介绍了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 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:43
查看更多