axios封装http请求

import axios from 'axios'

const HTTP_TIMEOUT = 15000;

export function httpPost(url, params = {},headers = {}) {
return axios.post(url, params, {
headers,
timeout: HTTP_TIMEOUT,
withCredentials: true,
}).then(resp=>resp.data);
} export function httpGet(url, params = {}) {
return axios.get(url, {
params,
timeout: HTTP_TIMEOUT,
withCredentials: true,
}).then(resp=>resp.data);
} export const errorCode = {
SUCCESS: 0,
} // 发送请求,并且对返回进行处理
// succConvert 函数-后台数据格式转换 function postAndConvertResp(url, params, succConvert, errConvert, headers = {}) {
return httpPost(url, params,headers)
.then(resp => {
return resp.err_code === errorCode.SUCCESS ?
succConvert(resp.result) :
errConvert ? errConvert(resp.err_code) : requestErrorHandler(resp.err_code, resp.err_msg);
})
} // 发送请求,并且对返回进行处理
function getAndConvertResp(url, params, succConvert, errConvert) {
return httpGet(url, params)
.then(resp => {
return resp.err_code === errorCode.SUCCESS ?
succConvert(resp.result) :
errConvert ? errConvert(resp.err_code) : requestErrorHandler(resp.err_code, resp.err_msg);
})
} // 默认错误处理
function requestErrorHandler(errCode, errMsg) {  
  throw new ServerRespError(errMsg);
}
// 前端自定义错误
export class ParamError extends Error {
constructor(message) {
super(message) this.errorType = 'ParamError'
}
} // 服务端返回错误
export class ServerRespError extends Error {
constructor(message) {
super(message) this.errorType = 'ServerRespError'
}
}

post请求参数处理:

function appendCommon2QueryStr(params) {
return data2ParamString(params);
} // param对象转换为paramStr
function data2ParamString(data) {
if (typeof data === 'string') {
return data;
}
return objectToParamString(data);
} // 将对象转换成键值对形式,只支持单层
function objectToParamString(data) {
var ret = '';
for (var key in data) {
ret = ret + key + '=' + encodeURIComponent(data[key]) + '&';
}
ret = ret.substr(0, ret.length - 1); // 去除最后的'&'
return ret;
} // 示例
export function example(reqData) {
let request = {
exam : reqData.exam
} request = appendCommon2QueryStr(request); return postAndConvertResp(URL, request, succConvert)
}
上一篇:设计模式《JAVA与模式》之调停者模式


下一篇:设置Spark运行程序时不显示log信息