UNPKG

muz-uni

Version:

自主开发的UniApp组件——Жидзин(Zidjin)系列组件库。

97 lines (85 loc) 4.1 kB
/** x-request-config V1.0 自动请求接口信息的动作 20230215 by Sieyoo, 赵向明 */ // import axios from 'axios'; import XTakeAt from './x-take-at.js'; const XRequestActionUniapp = function() {}; /** * function format 对Date的扩展,将 Date 转化为指定格式的String * @param {object} config 请求配置。可用的属性有:{url, method, root, headers, nodeData, nodeStatus, nodeStatusValue} * @param {object} param 请求接口中需要附带上的参数 * @desc 符号定义 * @return {Promise} 请求接口的返回信息 * @example 例子: * config = { * url: '/api/enroll_edit/{{id}}', * method: 'PUT', * root: 'http://www.xxx.com', * headers: { Authorization: localStorage.getItem('token') }, * nodeStatus: 'err', * nodeStatusValue: 0, * }; */ XRequestActionUniapp.request = function(config, param={}, prarmKey='data'){ // if(config.method === "GET"){ // config.headers['content-type'] = 'text/plain' // } else{ // config.headers['content-type'] = 'application/json' // } const headers = { 'Authorization': 'Bearer '+ uni.getStorageSync('token') || null, // #ifdef H5 'Content-Type': method === 'GET' ? '' : 'application/json', // #endif // 'Content-Type': 'application/x-www-form-urlencoded', // #ifdef MP-WEIXIN "Content-Type":"application/text", // 'Content-Type': method === 'GET' ? '' : 'application/json', // #endif ...config.headers, }; // console.log("XRequestActionUniapp:", config.headers, param); config.url = (config.rootUrl || '') + (config.url || ''); let newParam = {} // 过滤掉空信息,有BUG for(const key in param){ if(param[key]){ newParam[key] = param[key]; } } return new Promise((resolve, reject) => { // prarmKey = config.method === 'POST' || config.method === 'PUT' || config.method === 'PATCH' ? 'data' : 'params'; uni.request({ url: config.url, method: config.method || 'GET', data: newParam, // 是即将与请求一起发送的 URL 参数 timeout: 15000, header: config.headers, success: (res) =>{ // console.log("requestAction: res:", res) if (res.statusCode === 200) { if (res.data[config.nodeStatus || 'err'] === (config.nodeStatusValue || 0)) { // console.log('requestAction: success:', res); // console.log('requestAction: success 2:', config.nodeData); if(config.nodeData === undefined) config.nodeData = 'data'; // let tt = config.nodeData.split('.'); // let result = tt.length === 1 && tt[0] ? res.data[config.nodeData] : tt.length === 2 && res.data && res.data[tt[0]] && res.data[tt[0]][tt[1]] ? res.data[tt[0]][tt[1]] : res.data; let result = XTakeAt.getValue(res.data, config.nodeData, res.data) // console.log("XRequestActionUniapp result:", config.nodeData, result) resolve(result); } else { // this.$message({ message: res.data && res.data.msg, type: 'warning' }); console.warn('服务器连接正确,但返回接口或参数错误:', res.data.msg ? res.data.msg : res); reject(res.data.data ? res.data.data : res.data, res); } } else { reject(res.data.data ? res.data.data : res.data, res); } }, fail: err => { console.warn('网络地址没有响应或请求失败 config:', config, err); reject(err.data, res); } }) }); } export default XRequestActionUniapp