import ViewUI from 'view-design';
|
|
class HttpRequest {
|
constructor(baseUrl) {
|
this.baseUrl = baseUrl;
|
}
|
get(url) {
|
return new Promise((resolve, reject) => {
|
try {
|
fetch(this.baseUrl + url).then(res => {
|
if (res.ok)
|
return res.json()
|
else {
|
let err = JSON.stringify({
|
type: res.type,
|
status: res.status,
|
statusText: res.statusText
|
})
|
ViewUI.Message.error({
|
content: `调用${url}接口失败,` + err,
|
duration: 10
|
});
|
reject(err);
|
}
|
}).then(res => {
|
if (res.success)
|
resolve(res.data, res);
|
else {
|
reject(`调用${url}接口失败,error_code=${res.error_code},` + res.msg);
|
if (res.error_code != '0404') {
|
ViewUI.Notice.error({
|
desc: `调用${url}接口失败,error_code=${res.error_code},` + res.msg
|
});
|
}
|
}
|
}).catch(err => {
|
reject(`调用${url}接口失败,` + err);
|
ViewUI.Notice.error({
|
desc: `调用${url}接口失败,` + err
|
});
|
});
|
}
|
catch (err) {
|
reject(err);
|
}
|
});
|
}
|
post(url) {
|
return new Promise((resolve, reject) => {
|
try {
|
fetch(this.baseUrl + url, {
|
method: 'POST'
|
}).then(res => {
|
if (res.ok)
|
return res.json()
|
else {
|
let err = JSON.stringify({
|
type: res.type,
|
status: res.status,
|
statusText: res.statusText
|
})
|
ViewUI.Message.error({
|
content: `调用${url}接口失败,` + err,
|
duration: 10
|
});
|
reject(err);
|
}
|
}).then(res => {
|
if (res.success)
|
resolve(res.data, res);
|
else {
|
reject(`调用${url}接口失败,error_code=${res.error_code},` + res.msg);
|
if (res.error_code != '0404') {
|
ViewUI.Notice.error({
|
desc: `调用${url}接口失败,error_code=${res.error_code},` + res.msg
|
});
|
}
|
}
|
// resolve(res);
|
}).catch(err => {
|
reject(`调用${url}接口失败,` + err)
|
})
|
}
|
catch (err) {
|
reject(err);
|
}
|
})
|
}
|
form(url, data) {
|
return new Promise((resolve, reject) => {
|
try {
|
fetch(this.baseUrl + url, {
|
method: 'POST',
|
body: JSON.stringify(data),
|
headers: {
|
'Content-Type': 'application/json',
|
},
|
}).then(res => {
|
if (res.ok)
|
return res.json()
|
else {
|
let err = JSON.stringify({
|
type: res.type,
|
status: res.status,
|
statusText: res.statusText
|
})
|
ViewUI.Message.error({
|
content: `调用${url}接口失败,` + err,
|
duration: 10
|
});
|
// reject(err);
|
return res.json();
|
}
|
}).then(res => {
|
if (res.success)
|
resolve(res.data, res);
|
else {
|
if (!res.error_code) res.error_code = '';
|
if (!res.msg) res.msg = JSON.stringify(res);
|
reject(`调用${url}接口失败,error_code=${res.error_code},` + res.msg);
|
if (res.error_code != '0404') {
|
ViewUI.Notice.error({
|
desc: `调用${url}接口失败,error_code=${res.error_code},` + res.msg,
|
duration: 20
|
});
|
}
|
}
|
// resolve(res);
|
}).catch(err => {
|
ViewUI.Message.error({
|
content: `调用${url}接口失败,` + err,
|
duration: 10
|
});
|
reject(`调用${url}接口失败,` + err);
|
})
|
}
|
catch (err) {
|
reject(err);
|
}
|
})
|
}
|
}
|
|
export default HttpRequest;
|