前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >前端缓存http请求

前端缓存http请求

作者头像
windseek
发布2020-05-14 17:10:56
5240
发布2020-05-14 17:10:56
举报
文章被收录于专栏:杨龙飞前端杨龙飞前端
代码语言:javascript
复制
需求:
 1、 重复的请求,使用缓存
 2、 不重复的请求,允许发送
 3、 连续两次重复的发送,两次返回的结果是一样的,且第二次不发送请求
 
1、搭建前端服务
vue-cli 一步到位
代码语言:javascript
复制
<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>
代码语言:javascript
复制
2、后端服务,使用koa,也是一步到位搭建
代码语言:javascript
复制
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');
})
代码语言:javascript
复制
3、测试结果
实现点击多次北京
一次请求,但是执行结果是一样的
来回点击北京上海
一共两次请求,北京的得到是北京的请求结果,上海得到是上海的请求结果
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档