赞
踩
Axios
是一个基于 promise
的 HTTP
库,可以用在浏览器和 node.js
中。(本文围绕XHR)
axios
提供两个http
请求适配器,XHR
和HTTP
。
XHR
的核心是浏览器端的XMLHttpRequest
对象;
HTTP
的核心是node
的http.request
方法。
可以先熟悉一下axios官方文档
import axios from 'axios'; // 为给定ID的user创建请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 上面的请求也可以这样做 axios.get('/user', { params: {ID: 12345} }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 支持async/await用法 async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } }
axios
的API很友好,可以在项目中直接使用。
但是在大型项目中,http请求很多,且需要区分环境, 每个网络请求有相似需要处理的部分,不封装会导致代码冗余,破坏工程的可维护性,扩展性。
axios
封装没有一个绝对的标准,且需要结合项目中实际场景来设计。
请求成功,业务状态码200,能解析result给我,不用一层一层的去判断拿数据
请求失败,业务状态码非200,说明逻辑判断这是不成功的,全局message提示服务端的报错
http请求非200, 说明http请求都有问题,也全局message提示报错
http请求或者业务状态码401都做注销操作
统一文件下载处理
全局的loading配置, 默认开启,可配置关闭(由于后端的问题,经常会让前端加防抖节流或者loading不让用户在界面上疯狂乱点)
常见以下三种
参数会直接放在请求体中,以JSON格式的发送到后端。这也是axios请求的默认方式。这种类型使用最为广泛。
请求体中的数据会以 普通表单形式(键值对) 发送到后端。
参数会在请求体中,以标签为单元,用分隔符(可以自定义的boundary)分开。既可以上传键值对,也可以上传文件。通常被用来上传文件的格式。
import _Vue from 'vue'; import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios'; import { CryptUtil } from '@/utils/CryptUtil'; // import { MAINHOST, QAHOST, commonParams } from '@/config'; // import { getToken } from '@/utils/common'; // import qs from 'qs'; import router from '@/router' class AxiosHttpRequest { private axios: AxiosInstance; private dischargedApi: Array<string> = [ '/system/api/searchHumanName', '/system/api/login', '/system/api/template', '/system/api/info/sysconfig/item', '/system/api/unitinfo/loadaddress' ] constructor(ax: any) { this.axios = ax; // axios 配置 this.axios.defaults.timeout = 120 * 1000; // this.axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? MAINHOST : QAHOST; // @ts-ignore this.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // this.axios.defaults.baseURL = 'http://119.3.251.200:8097'; // http request 拦截器 this.axios.interceptors.request.use( (config: AxiosRequestConfig) => { // 在此处添加请求头等,如添加token if (sessionStorage.getItem('token')) { // @ts-ignore config.headers['Authorization'] = sessionStorage.getItem('token'); // @ts-ignore config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + ''); } else { // @ts-ignore if (this.dischargedApi.includes(config.url)) { // @ts-ignore config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJISSI6LTEsIlVJIjoxLCJITiI6IumZtuaYjum-mSIsIlJJIjoiIiwiVU4iOiLlub_opb_lo67ml4_oh6rmsrvljLoiLCJVQyI6Ii8xLyJ9.DAWCZpyQSAngIv4NBIxxz19mrLGvHdZI8WdNim5wlI0yZoa0WkHCrb-tyDY4v1MpbpEl4TWEOndnZmxxdma0YQ'; // @ts-ignore config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + ''); } } let sysConfigMap = JSON.parse(sessionStorage.getItem('sysConfigMap') as string); if (sysConfigMap) { let WEB_API_ENCRYPT_LIST = JSON.parse(sessionStorage.getItem('sysConfigMap') as string).WEB_API_ENCRYPT_LIST || []; if (WEB_API_ENCRYPT_LIST.length > 0) { WEB_API_ENCRYPT_LIST = WEB_API_ENCRYPT_LIST.split(';'); for (let i = 0; i < WEB_API_ENCRYPT_LIST.length; i++) { // @ts-ignore if (config.url.indexOf(WEB_API_ENCRYPT_LIST[i]) > -1) { // @ts-ignore config.headers['encry'] = 'true'; config.data = { data: CryptUtil.desEncrypt(JSON.stringify(config.data)) } break; } } } } return config; }, (error: any) => { return Promise.reject(error); } ); // http response 拦截器 this.axios.interceptors.response.use( (response: AxiosResponse) => { if (response.headers['encry'] === 'true') { // @ts-ignore response.data['data'] = JSON.parse(CryptUtil.desDecrypt(response.data.data)); } return response; }, (error: any) => { if (error.response.data?.message) { error.message = error.response.data.message; } else 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.includes('timeout')) { error.message = '请求超时'; } else { // error.message = '连接服务器失败,请联系管理员'; } if (error && error.response && (error.response.status === 401 || error.response.status === 403)) { _Vue.prototype.$message.warning({ content: "token失效,请重新登录", duration: 3, onClose: () => { // 清除token sessionStorage.clear(); // window.close(); router.push({ name: 'Login' }); } }); } else { _Vue.prototype.$message.error( error.message ); } return Promise.reject(error.response); } ); } public get(url: string, params: object, config: object) { //增加时间戳 防止缓存 params = { _t: new Date().getTime(), ...params } return this.axios({ method: 'get', url, params, ...config, }).then( (res: any) => { if (res && res.data) { if (!res.data.ok) { _Vue.prototype.$message.error( res.data.message ? res.data.message : "" ); return; } return res.data.data || res.data.dataMap; } } ); } // 获取静态资源 public getStatic(url: string, params: object, config: object) { //增加时间戳 防止缓存 params = { _t: new Date().getTime(), ...params } return this.axios({ method: 'get', url, params, ...config, }).then( (res: any) => { if (res && res.data) { return res.data; } else { _Vue.prototype.$message.error('资源获取失败!'); } } ); } public getTrace(url: string, params: object, config: object) { //增加时间戳 防止缓存 params = { _t: new Date().getTime(), ...params } return this.axios({ method: 'get', url, params, ...config, }).then( (res: any) => { if (res && res.data) { return res.data.data || res.data.dataMap; } } ); } public post(url: string, params: object) { return this.axios({ method: 'post', url, // data: qs.stringify(params), data: params, }).then( (res: any) => { if (res && res.data) { if (!res.data.ok) { _Vue.prototype.$message.error( `${res.data.message ? `${res.data.message}` : ""}`, ); return; } return res.data.data || res.data.dataMap; } } ); } public postJson(url: string, params: object, config: object, need:boolean = true) { return this.axios({ method: 'post', url, data: JSON.stringify(params), headers: { "Content-Type": "application/json", ...config }, transformRequest: [function (data, headers) { // @ts-ignore if (!need && headers.Authorization) { // @ts-ignore delete headers.Authorization; } // @ts-ignore if (!need && headers.Verify) { // @ts-ignore delete headers.Verify; } return data; }] }).then( (res: any) => { if (res && res.data) { if ((res.data.hasOwnProperty("success") && !res.data.success) || (res.data.hasOwnProperty("hasError") && res.data.hasError)) { _Vue.prototype.$Notice.error({ title: "请求失败", desc: res.data.message ? res.data.message : "" }); return; } return res.data.data || res.data.dataMap; } } ); } public uploadFile(url: string, data: FormData, config1?: object) { let config = { // 请求头信息 headers: { 'Content-Type': 'multipart/form-data' }, ...config1 }; return this.axios.post(url, data, config).then( (res: any) => { if (res && res.data) { if (!res.data.ok) { _Vue.prototype.$Notice.error({ title: "请求失败", desc: res.data.message ? res.data.message : "" }); return; } return res.data.data || res.data.dataMap; } } ); } public getData(url: string, params: object) { return this.axios({ method: 'get', url, params: params, responseType: 'blob' }).then((res) => { let url = window.URL.createObjectURL(new Blob([res.data])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; // @ts-ignore link.setAttribute('download', params['fileName']); document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } public postData(url: string, fileName: string, params: object) { return this.axios({ method: 'post', url, data: params, responseType: 'blob' }).then((res) => { let url = window.URL.createObjectURL(new Blob([res.data])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; // @ts-ignore link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } } const $axios: AxiosHttpRequest = new AxiosHttpRequest(axios); export function AxiosRequest(Vue: typeof _Vue): void { Vue.prototype.$axios = $axios; }
async loadReportFields() {
this.tableData = await Service.loadReportFields({ reportId: this.reportId });
}
import Vue from "vue";
const config = `/report/api/config/`;
const configCond = `/report/api/config/cond/`;
const configStatis = `/report/api/config/statis/`;
const configAuth = `/report/api/config/auth/`;
const statis = `/report/api/statis/`;
export const loadReportFields = (params: any) => {
return Vue.prototype.$axios.get(`${config}loadfields`, params);
};
export const updateReport = (params: any) => {
return Vue.prototype.$axios.post(`${config}update`, params);
};
参考 https://juejin.cn/post/6999932338566070308#heading-12
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。