封装axios并创建请求函数
程序员文章站
2022-07-04 09:26:23
封装axiosajax.js/*封装axios函数的返回值是promise对象统一处理请求异常*/import axios from "axios";export default function ajax(url, data = {}, type = "GET") { return new Promise((resolve, reject) => { let promise; //1、执行异步ajax请求 if (type === "GET") {...
封装axios
ajax.js
/*
封装axios
函数的返回值是promise对象
统一处理请求异常
*/ import axios from "axios"; export default function ajax(url, data = {}, type = "GET") { return new Promise((resolve, reject) => { let promise; //1、执行异步ajax请求 if (type === "GET") { promise = axios.get(url, { params: data }); } else { promise = axios.post(url, data); } promise .then(response => { //2、如果成功,调用resolve() resolve(response); }) .catch(error => { //3、如果失败,不调用reject(),而是提示异常信息(可以结合第三方框架) alert("请求出错"); }); }); }
请求函数
index.js
/*
接口请求函数
*/ import ajax from "./ajax"; //登录 export const reqLogin = (username, password) => ajax("/login", { username, password }, "POST");
本文地址:https://blog.csdn.net/weixin_41897680/article/details/107892609
上一篇: xts运行命令
下一篇: 愤怒的小鸟P2831