This article introduces Vue2 SSR cached API data and shares it with you, as follows:
1. Install cache dependencies: lru-cache
npm install lru-cache --dev
2. API configuration file
var LRU = require('lru-cache') let api if (process.__API__) { api = process.__API__ } else { api = process.__API__ = { api: 'http://localhost:8080/api/', cached: LRU({ max: 1000, maxAge: 1000 * 60 * 15 }), cachedItem: {} } } = api
lru-cache under configuration
3. Encapsulate the api
import axios from 'axios' import qs from 'qs' import md5 from 'md5' import config from './' export default { post(url, data) { const key = md5(url + (data)) if ( && (key)) { return ((key)) } return axios({ method: 'post', url: + url, data: (data), // Other configurations }).then(res => { if ( && ) (key, res) return res }) } }
We use axios library, because axios can be used in nodejs and browsers
And separate the node end and the browser end
import config from './'
const key = md5(url + (data))
Generate a unique key through url and parameters
if ( && (key)) { return ((key)) }
if ( && ) (key, res)
If the cache is enabled and the interface specifies the cache, write the data returned by the API to the cache
Notice:
This API will handle all requests, but many requests do not need to be cached, so if you need to cache, you can add a cache: true in the data passed in, such as:
('/api/test', {a: 1, b:2, cache: true})
If you do not need cache, just pass the value normally.
Of course, there are many ways to cache the tag here, and you don't have to use this one
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.