nuxt.js - How to cache axios call at server side for all clients

这一生的挚爱 提交于 2021-01-01 05:15:50

问题


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.


回答1:


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

First add a local module to nuxt.config.js

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

Then

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

and

// 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.

solution found on: https://github.com/nuxt-community/axios-module/issues/99




回答2:


here is the new solution for cache the whole page

even you can cache consistent api like menu if you need

https://www.npmjs.com/package/nuxt-perfect-cache

npm i nuxt-perfect-cache

// nuxt.config.js

modules: [
    [
        'nuxt-perfect-cache',
        {
          disable: false,
          appendHost: true,
          ignoreConnectionErrors:false, //it's better to be true in production
          prefix: 'r-',
          url: 'redis://127.0.0.1:6379',
          getCacheData(route, context) {          
            if (route !== '/') {
              return false
            }
            return { key: 'my-home-page', expire: 60 * 60 }//1hour
          }
        }
      ]
]

then for cache your api response in redis for all clients:

asyncData(ctx) {
    return ctx.$cacheFetch({ key: 'myApiKey', expire: 60 * 2 }, () => {
      console.log('my callback called*******')
      return ctx.$axios.$get('https://jsonplaceholder.typicode.com/todos/1')
    })
  }


来源:https://stackoverflow.com/questions/60046814/nuxt-js-how-to-cache-axios-call-at-server-side-for-all-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!