npm install @nuxtjs/axios --save
export default {
modules: [
'@nuxtjs/axios',
],
axios: {
// proxy: true
}
}
async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return { ip }
}
methods: {
async fetchSomething() {
const ip = await this.$axios.$get('http://icanhazip.com')
this.ip = ip
}
}
export default function ({ app, $axios, redirect }) {
const API = {};
API.getPublicKey = function (params) {
return $axios({
url: '/api/serviceConvergeRsa',
method: 'get',
data: params,
headers: {
'encrypt': 1
},
})
};
API.getServiceList = function (data, header={}) {
return $axios({
url: `/api/getServiceConvergeList`,
method: 'get',
params: data,
headers: header
})
};
app.api = API;
}
export default {
plugins: [
'~/plugins/api'
],
modules: [
'@nuxtjs/axios',
],
// 需要代理,可以打开底下的注释
// axios: {
// proxy: true
// },
// proxy: {
// '/api/': 'https://www.jianshu.com'
// },
}
async asyncData(context) {
// 请检查您是否在服务器端
// if (process.server) {}
const RSA_DATA = await context.app.api.getPublicKey({});
return RSA_DATA
}
npm install lru-cache --save
用于缓存数据
const LRU = require('lru-cache')
const cachePage = new LRU({
// 最大缓存数量
max: 10,
// 缓存过期时间(ms),缓存1小时
maxAge: 60 * 60 * 1000
})
module.exports = cachePage
const globalCache = require('./globalCache');
export default function ({ query, app, $axios, redirect }, inject) {
const API = {};
API.getPublicKey = function (params) {
// 页面请求附带refresh参数时,强制刷新数据
if (globalCache.get('serviceConvergeRsa') && globalCache.get('RSA_PUBLIC_KEY') && !query.refresh) {
return Promise.resolve(globalCache.get('serviceConvergeRsa'));
}
return $axios({
url: '/api/serviceConvergeRsa',
method: 'get',
data: params,
headers: {
'encrypt': 1
},
}).then(function (res) {
var RSA_DATA = res.data
if (RSA_DATA.code === 200) {
console.log('刷新serviceConvergeRsa密钥数据~');
// 设置缓存数据
globalCache.set('RSA_PUBLIC_KEY', RSA_DATA.data.rsaPublicKey, Number(RSA_DATA.data.expireTime));
globalCache.set('serviceConvergeRsa', RSA_DATA, Number(RSA_DATA.data.expireTime));
}else{
console.error('serviceConvergeRsa',RSA_DATA.message)
}
return Promise.resolve(res.data);
})
};
API.getServiceList = function (data, header={}) {
var globalCacheKey = 'getServiceConvergeList'
// 如果接口缓存有数据,且页面请求没有refresh参数,则返回缓存数据
if (globalCache.get(globalCacheKey) && !query.refresh) {
return Promise.resolve(globalCache.get(globalCacheKey));
}
return $axios({
url: `/api/getServiceConvergeList`,
method: 'get',
params: data,
headers: header
}).then(function (res) {
var result = res.data;
if (result.code == 200 && result.data) {
console.log('刷新getServiceConvergeList服务汇聚列表数据~');
// 设置缓存数据
globalCache.set(globalCacheKey, res.data);
}else{
console.error('getServiceConvergeList',result.message)
}
return Promise.resolve(res.data);
})
};
app.api = API;
}
其他配置以及使用 参考前面的api封装。
https://juejin.cn/post/6844903623483195399