果冻

// request.js /** * @intro: http统一封装. */ import axios from 'axios'; /** * 判断是否是 FormData * @param formData * @returns {boolean} */ const isFormData = (formData) => !!formData && Object.prototype.toString.call(formData) === '[object FormData]'; /** * 是否是表单数据格式化 * @param d * @returns {boolean} */ const isFormScheme = (d) => typeof d === 'string' && /([^&?]*)=([^&?]*)/i.test(d); /** * 判断接口返回的code是否正确 * @param code 接口返回的code * @returns {boolean} */ const judgeCode = (code) => /^0$/.test(code); /** * 判断接口返回的code是否未登录 * @param code 接口返回的code * @returns {boolean} */ const judgeUnLoginCode = (code) => /^(10103|10104|10105|10106|10107|10108)$/.test(code); const service = axios.create({ // 设置全局默认的headers headers: { 'Content-Type': 'application/json', }, // 设置请求超时设置 timeout: 30000, responseType: 'json', // 请求转换 transformRequest: [ (data, headers) => { // 这里可以在请求头中增加token,如果后台是jwt这种鉴权的话 const { token } = 用户token对象; // eslint-disable-next-line no-param-reassign if (token && !headers.Authorization) headers.Authorization = `Bearer ${token}`; // 表单上传 if (isFormData(data)) return data; // 普通表单 if (isFormScheme(data)) { headers['Content-Type'] = 'application/x-www-form-urlencoded'; return data; } return JSON.stringify(data); }, ], });
posted @ 2022-06-02 19:59  伤神相约科技  阅读(21)  评论(0)    收藏  举报