前端缓存http请求
Posted windseek
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端缓存http请求相关的知识,希望对你有一定的参考价值。
需求:
1、 重复的请求,使用缓存
2、 不重复的请求,允许发送
3、 连续两次重复的发送,两次返回的结果是一样的,且第二次不发送请求
1、搭建前端服务
vue-cli 一步到位
<template> <div class="hello"> <button v-on:click="getrs(1)"> 北京 </button> <button v-on:click="getrs(2)"> 上海 </button> </div> </template> <script> let obj = {}; let flagArr = []; let objPromise = {}; export default { name: ‘HelloWorld‘, props: { msg: String }, methods: { getrs(cityId) { this.getCity(cityId).then((data) => { console.log(data); }) }, getCity(cityId) { let promise = new Promise((resolve) => { if(obj[cityId]) { /** * 如果命中缓存不发送请求了 */ return resolve(obj[cityId]); } if(!flagArr.includes(cityId)) { flagArr.push(cityId); /** * 第一次调用的话,请求数据,放到obj里 */ this.axios.get(‘http://localhost:3000/?cityid=‘+cityId).then((response)=>{ return response }).catch((response)=>{ return response }).then( (data) => { let index = flagArr.indexOf(cityId); flagArr.splice(index, 1); obj[cityId] = data; resolve(obj[cityId]) } ) } }) objPromise[cityId] = promise; if(flagArr.includes(cityId)) { /** * 连续第二次调用的话,如果结果还没有回来,返回上个相同请求的promise */ return objPromise[cityId]; } return promise; } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
2、后端服务,使用koa,也是一步到位搭建
const Koa = require(‘koa‘) const app = new Koa() app.use(async (ctx, next)=> { ctx.set(‘Access-Control-Allow-Origin‘, ‘*‘); ctx.set(‘Access-Control-Allow-Headers‘, ‘Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild‘); ctx.set(‘Access-Control-Allow-Methods‘, ‘PUT, POST, GET, DELETE, OPTIONS‘); if (ctx.method == ‘OPTIONS‘) { ctx.body = 200; } else { await next(); } }); app.use(async(ctx)=>{ let url =ctx.url //从request中获取GET请求 let request =ctx.request let req_query = request.query let req_querystring = request.querystring //从上下文中直接获取 let ctx_query = ctx.query let ctx_querystring = ctx.querystring ctx.body={ url, } }) app.listen(3000,()=>{ console.log(‘server is starting at port 3000‘); }) const Koa = require(‘koa‘) const app = new Koa() app.use(async (ctx, next)=> { ctx.set(‘Access-Control-Allow-Origin‘, ‘*‘); ctx.set(‘Access-Control-Allow-Headers‘, ‘Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild‘); ctx.set(‘Access-Control-Allow-Methods‘, ‘PUT, POST, GET, DELETE, OPTIONS‘); if (ctx.method == ‘OPTIONS‘) { ctx.body = 200; } else { await next(); } }); app.use(async(ctx)=>{ let url =ctx.url //从request中获取GET请求 let request =ctx.request let req_query = request.query let req_querystring = request.querystring //从上下文中直接获取 let ctx_query = ctx.query let ctx_querystring = ctx.querystring ctx.body={ url, } }) app.listen(3000,()=>{ console.log(‘server is starting at port 3000‘); })