request.js
import axios, {AxiosRequestConfig} from "axios";
import qs from "qs";
// 创立 axios 实例
const instance = axios.create({
baseURL: process.env.VUE_APP_BASEURL,
timeout: 6000,
// headers: {
// "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
// token:
// "MTY1Mjk1Mjg4OC42ODM2Nzg0JjJkNzUyOWQwOWU3NTU2OTE0OTU4NzI3ODUxNzkwYTNjZGMwZmRjNjAzNGQ4MGE1YzFkODE1NGVmYzk4MmMyYjM=",
// },
});
// 申请拦截器
instance.interceptors.request.use((config) => {
// 申请头和 token 判断等
return config;
},
(err) => {return Promise.reject(err);
}
);
// 响应拦截器
instance.interceptors.response.use((res) => {return res.data;},
(error) => {if (error && error.response) {switch (error.response.status) {
case 400:
error.message = "申请谬误 (400)";
break;
case 401:
error.message = "未受权, 请登录 (401)";
break;
case 403:
error.message = "回绝拜访 (403)";
break;
case 404:
error.message = ` 申请地址出错: ${error.response.config.url}`;
break;
case 405:
error.message = "申请办法未容许 (405)";
break;
case 408:
error.message = "申请超时 (408)";
break;
case 500:
error.message = "服务器外部谬误 (500)";
break;
case 501:
error.message = "服务未实现 (501)";
break;
case 502:
error.message = "网络谬误 (502)";
break;
case 503:
error.message = "服务不可用 (503)";
break;
case 504:
error.message = "网络超时 (504)";
break;
case 505:
error.message = "HTTP 版本不受反对 (505)";
break;
default:
error.message = ` 连贯谬误: ${error.message}`;
}
} else {if (error.message == "Network Error")
error.message == "网络异样,请查看后重试!";
error.message = "连贯到服务器失败,请分割管理员";
}
return Promise.reject(error);
}
);
//get 申请
export function get(url: string, params = {}) {return new Promise((resolve, reject) => {
instance
.get(url, {params: params,})
.then((response) => {resolve(response);
})
.catch((err) => {reject(err);
});
});
}
//post 申请
export function post(url: string, params = {}) {return new Promise((resolve, reject) => {
instance
.post(url, qs.stringify(params))
.then((response) => {resolve(response);
})
.catch((err) => {reject(err);
});
});
}
// delete 申请
export function deleteFn(url: string, params: AxiosRequestConfig<any> | undefined) {return new Promise((resolve, reject) => {
instance
.delete(url, params)
.then((response) => {resolve(response);
})
.catch((err) => {reject(err);
});
});
}
// put 申请
export function put(url: string, params: any) {return new Promise((resolve, reject) => {
instance
.put(url, qs.stringify(params))
.then((response) => {resolve(response);
})
.catch((err) => {reject(err);
});
});
}
export default instance;
调用:
import {get, post, deleteFn, put} from "../utils/request";
export const login_api = (params: {} | undefined) => {return get("/XXXX/xxx", params);
};
在.vue 中应用之前先 import 进来就能够了