前端緩存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');
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM