1. 安装缓存依赖: lru-cache

npm install lru-cache --dev

2. api 配置文件

config-server.js

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: {}
    }
}

module.exports = api

配置下lru-cache

3. 封装下 api

import axios from 'axios'
import qs from 'qs'
import md5 from 'md5'
import config from './config-server.js'

export default {
    post(url, data) {
        const key = md5(url + JSON.stringify(data))
        if (config.cached && config.cached.has(key)) {
            return Promise.resolve(config.cached.get(key))
        }
        return axios({
            method: 'post',
            url: config.api + url,
            data: qs.stringify(data),
            // 其他配置
        }).then(res => {
            if (config.cached && data.cache) config.cached.set(key, res)
            return res
        })
    }
}

ajax 库我们用axios, 因为axios在 nodejs 和 浏览器都可以使用
并且将 node 端和浏览器端分开封装

import config from './config-server.js'
const key = md5(url + JSON.stringify(data))

通过 url 和参数, 生成一个唯一的 key

if (config.cached && config.cached.has(key)) {
    return Promise.resolve(config.cached.get(key))
}
if (config.cached && data.cache) config.cached.set(key, res)

判断下是不是开启了缓存, 并且接口指定缓存的话, 将 api 返回的数据, 写入缓存

注意:
这个 api 会处理所有的请求, 但是很多请求其实是不需要缓存的, 所以需要缓存可以在传过来的 data 里, 添加个 cache: true, 如:

api.post('/api/test', {a: 1, b:2, cache: true})

不需要缓存的直接按正常传值即可
当然这里标记是不是要缓存的方法有很多, 不一定要用这一种

发表评论
木槿阿伦
回复 @7777: 问题解决了饿吗?
7777
回复 @Duke: 你好,你这个问题解决了么? 希望博主看见能够回答,感激不尽,刷新后的页面为什么不会被缓存?
Duke
F5刷新后 缓存就没了 何解 (●゚ω゚●)
space
能不能换头像啊。。。
root
回复 @root: this is a test too !
root
test!