公司用react开发项目,特意封装了一个axios请求 代码如下:
import axios from 'axios'
/**
* 基础配置
* 更多配置请参考 https://github.com/axios/axios
* @param {*} url 请求地址
* @param {*} data 参数
* @param {*} type 请求类型,默认post
*/
let HttpServer = async (url, data = {}, type = 'GET') => {
let headers = {
'content-type': 'application/x-www-form-urlencoded'
};
let config = {
url: "http://192.168.0.157/"+url,
method: type,
params: data,
timeout: 6000, // 超时时间
headers: headers,
responseType: 'json',
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认的
},
maxRedirects: 5
};
let response = null;
try {
response = await axios(config);
if(response.status == 200){
if(response.data.code != "200"){
alert(response.data.message);
response = Promise.reject(response);
}
}else if(response.status != 200){
alert("服务器请求发生错误,请联系管理员");
}
} catch (error) {
alert(error);
response = Promise.reject(error);
}
return response;
};
export default HttpServer;
使用方式
httpServer("url",params).then(function(data){
console.log(data)
});
网友评论