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) }