标签:02 function 请求 get 菜菜 request --- products data
网络请求全局封装
1. 安装请求接口插件
npm i axios
2. utils目录下封装 (request.js)
import axios from "axios"
// 创建实例
const instance = axios.create({
// 网络请求的基础地址。。设置基础地址后 发送请求时可以省略
baseURL:"http://localhost:1337"
});
// 封装get 请求 。axios get请求,参数为路径与配置信息
export const get =(url,params)=> instance.get(url,{params});
// post 请求
export const post = (url,data)=>instance.post(url,data);
3. 调用接口获取数据 ---use
1. 引入 请求方法
<script>
import {get} from "../utils/request"
// 创建成功后请求数据
created(){
get("/api/v1/products").then((res)=>{
// 不需要res.data.因为封装请求时,全局响应拦截返回值为res.data
console.log(res);
this.datas=res.data
})
},
</script>
2. 全局请求拦截,与全局响应拦截
// 全局请求拦截 axios 拦截器,
// Add a request interceptor
instance.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// 全局响应拦截,返回结果之后执行
// Add a response interceptor
instance.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
## 多操作一层,返回res.data
return response.data;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
4. 同步方式调用接口 (async/await)
<script>
import {get} from "../utils/request";
export default{
async created(){
const products = await get ("/api/v1/products");
console.log(products)
}
}
## 同步方式,不需要(.then)方法
</script>
5. API进化 ,load 封装 (services)
-
封装 服务 (方法)
import {get} from "../utils/request"; export function LoadProductsAPI(){ return get("/api/v1/products") }
-
use,替换get请求,直接调用API方法
<script> import LoadProductsAPI from "../serviices/products"; export default{ async created(){ const products = await LoadProductsAPI(); console.log(products) } } ## 同步方式,不需要(.then)方法 </script>
标签:02,function,请求,get,菜菜,request,---,products,data 来源: https://blog.csdn.net/weixin_44290588/article/details/122733079
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。