get 请求
axios.get(url,
{
headers: {
'Authorization': 'Bearer ' + token,
"Cookie" : 'sessionId=' + sessionId + '; recId=' + recId,
...
},
params: {
param1: string,
param2: string
},
...
}
)
.then(res => fn)
.catch(e => fn)
Post 请求
axios.post(url,
{
data: data,
...
},
{
headers: {
'Authorization': 'Bearer ' + token,
"Cookie" : 'sessionId=' + sessionId + '; recId=' + recId,
...
}
}
)
.then(res => fn)
.catch(e => fn)
axios.request({config}) 配置项
export interface Axios RequestConfig {
url?: string
method?: string
baseURL?: string
transformRequest?: Axios Transformer I Axios Transformer[
transformResponse?: AxiosTrans former Axios Trans former[]
headers?: any i
params serializer?:(params: any)=> string
data?: any;
timeout?: number;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials:
responseType?: string
xsrfCookieName?: string
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any )= void;
onDownloadProgress?: (progressEvent: any)=> void;
maxContentLength?: number
validateStatus?: (status: number )= boolean;
maxRedirects?: number;
httpagent?:any
httpsagent?:anyi
proxy ?: Axios Proxy Config false
cancel Token?: CancelToken
}
代码参考
// 封装
request(url, method, { params, data, headers = {}, isApi = true, ...others } = {}) {
const conf = {
...config,
...this.cfg,
...others,
url: formatUrl(url, isApi, this.apiPrefix),
method,
headers,
// disable browser's cache
// always make a new request
params: {
...params,
timestamp: new Date().getTime()
},
data
};
conf.headers = omitBy(conf.headers, v => typeof v === 'undefined');
return this.$http.request(conf);
}
get(url, params, config = {}) {
return this.request(url, 'GET', { ...config, params });
}
post(url, data, config = {}) {
return this.request(url, 'POST', { ...config, data,
headers: { 'X-RESOURCEID': getResourceId() } // 可单独设置
});
}
// 引用
getBillingGroup(cptCode,level) {
return this.get('/hr/hrBillingGroup/get',{cptCode,level})
}
// 佣金规则 billingGroup
RSbillingGroup(data) {
return this.post('/hr/hrBillingGroup/billingGroup',data)
}
axios 可通过Axios自带的qs.stringify()对参数进行序列化
序列化后Content-Type就变成了application/x-www-form-urlencoded
它声明了请求数据会以键值对(普通表单形式)的形式发送
//添加请求拦截器
axios.interceptors.request.use((config) => {
//在发送请求之前做某件事
if (config.method === 'post') {
config.data = qs.stringify(config.data);
}
config.cancelToken = new axios.CancelToken(function (cancel) {
store.commit('pushToken', { cancelToken: cancel })
})
return config;
}, (error) => {
iview.Notice.warning({
title: '参数错误'
});
return Promise.reject(error);
});