## >request.js
对axios进行基础设置
~~~
import axios from 'axios' //引入axios
import qs from 'qs'
axios.defaults.timeout = 10000; //设置请求超时
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // 设置post请求头
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
console.log(config);
// 在发送请求前可以对请求数据进行处理
return config;
}, function (error) {
console.log(error);
// 请求错误时所作操作
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
console.log(response);
// 请求成功后的操作,如返回res.data.data
return response;
}, function (error) {
console.log(error);
// 对响应错误处理,如根据错误编码给出不同提示
return Promise.reject(error);
});
/**
* axios请求
* @param url 请求地址
* @param method {METHOD} http method
* @param params 请求参数
* @returns {Promise<AxiosResponse>}
*/
async function request(url, method, params, config) {
return axios[method](url, params, config);
}
//不同的请求方式配置
const http = {
get: (url, params, config = {}) => {
return request(
url,
"get",
{
params:params
},
config
);
},
post: (url, params, config = {}) => {
let param = params;
return request(url, "post", param, config);
},
put: (url, params, config = {}) => {
return request(url, "put", params, config);
},
delete: (url, params, config = {}) => {
return request(
url,
"delete",
{
params:params
},
config
);
},
requestJson: (
url,
params,
type,
config = {
headers: {
"Content-Type":"application/json"
}
}
) => {
return request(url, type, params, config);
},
\**
\* 导入文件
\* @param {String} url \[请求的url地址\]
\* @param {Object} params \[请求时携带的参数\]
*/
postForm: (
url,
params,
config = {
headers: {
"content-Type":"multipart/form-data"
}
}
) => {
return request(url, "post", params, config);
}
};
export default http;
~~~
~~~