封装axios的接口请求数据方法
生活随笔
收集整理的這篇文章主要介紹了
封装axios的接口请求数据方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
lib文件夾中http.js文件的內容
?
包含了數據請求,路由的攔截,同時向外界暴露的是一個方法,方法內有三個參數,分別為請求的方式,地址,數據
1 import axios from 'axios'; 2 import qs from 'qs'; 3 4 const server=axios.create({ 5 timeout:5000, 6 withCredentials:true 7 }) 8 9 server.interceptors.request.use((config)=>{ 10 if(config.method.toUpperCase()=="GET"){ 11 config.params={...config.data} 12 }else if(config.method.toUpperCase()=="POST"){ 13 config.headers["content-type"] = "appliaction/x-www-form-urlencoded"; 14 config.data=qs.stringify(config.data); 15 } 16 vm.handlemount(); 17 return config; 18 },(err)=>{ 19 Promise.reject(err); 20 }) 21 22 23 server.interceptors.response.use((res)=>{ 24 if(res.statusText=="OK"){ 25 vm.handleDestory(); 26 return res.data 27 } 28 },(err)=>{ 29 Promise.reject(err); 30 }) 31 32 33 export default (method,url,data={})=>{ 34 if(method.toUpperCase()=="GET"){ 35 return server.get(url,{ 36 params:data 37 }) 38 }else if(method.toUpperCase()=="POST"){ 39 return server.post(url,data); 40 } 41 }數據請求
1 http("get", "/client/v1/goods/newactivityTemplate?aTId=130").then(data => { 2 3 })上面方法可以進行封裝
API文件中movie.js文件中的內容為
import http from "utils/http.js"export const city_api = ()=>http("get","/api/cityList")export const movie_coming_api = (cityId=10)=>http("get","/api/movieComingList",{cityId:cityId})在請求接口數據的時候的代碼為
import {city_api} from "api/movie"async created() {if(!sessionStorage.getItem("comingList")){let data = await movie_coming_api(this.cityId); this.comingList = data.data.comingList;sessionStorage.setItem("comingList",JSON.stringify(data.data.comingList))}},async handleGetCityAction({commit}){let data = await city_api(); commit("handleGetCityMutation",data.data.cities)}
?
轉載于:https://www.cnblogs.com/muzishijie/p/11348964.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的封装axios的接口请求数据方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爬取w3c课程—Urllib库使用
- 下一篇: Unity3D实践系列03,使用Visu