使用axios的Promise封装
使用 axios 的 Promise 封装
简单的 axios 封装 ajax.js
import axios from "axios";
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
function process(res) {
let body = res.data;
if (body.code === 0) {
return new Promise(function (resolve, reject) {
resolve(body.data);
});
} else {
return new Promise(function (resolve, reject) {
reject({ code: body.code, msg: body.msg });
});
}
}
function get(uri, params) {
return axios.get(uri, { params: params, headers: headers }).then((res) => {
return process(res);
});
}
function post(uri, params) {
let data = new FormData();
for (let item in params) {
data.append(item.toString(), params[item].toString());
}
return axios
.post(uri, data, {
headers: headers,
})
.then((res) => {
return process(res);
});
}
function remove(uri, params) {
return axios
.delete(uri, {
params: params,
headers: headers,
})
.then((res) => {
return process(res);
});
}
const ajax = {
get: get,
post: post,
delete: remove,
};
export { ajax };