前端缓存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 objPromise = {};
 
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    getrs(cityId) {
      this.getCity(cityId).then((data) => {
        console.log(data);
      })
    },
    getCity(cityId) {
        if(objPromise[cityId]) {
          /**
           * 连续第二次调用的话,如果结果还没有回来,返回上个相同请求的promise
           */
          return objPromise[cityId];
        }
        let promise = new Promise((resolve) => {
            this.axios.get('http://localhost:3000/?cityid='+cityId).then((response)=>{
                return response
            }).catch((response)=>{
                return response
            }).then(
                (data) => {
                    resolve(data)
                }
            )
        })
        objPromise[cityId] = promise;
        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');
})
原文地址:https://www.cnblogs.com/windseek/p/12885687.html