HttpUtils 工具类
const formData = Symbol();
export default class IHttpUtils {
/**
* GET 请求
*
* @static
* @param {*} { url }
* @returns
* @memberof IHttpUtils
*/
static get({ url }){
return new Promise((resolve, reject)=> {
fetch(url)
.then(response => response.json())
.then(responseJson => {
resolve(responseJson);
})
.catch(error => {
reject(error);
})
})
}
/**
* POST 请求
*
* @static
* @param {*} { url, data }
* @returns
* @memberof IHttpUtils
*/
static post({ url, data }){
return new Promise((resolve,reject)=> {
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'application/x-www-form-urlencoded'
},
body: this[formData](data)
})
.then(response=>response.json())
.then(result=> {
resolve(result);
})
.catch(error=>{
reject(error);
})
})
}
/**
* 对象转表单数据
*
* @static
* @param {*} data
* @returns
* @memberof IHttpUtils
*/
static [formData] (data) {
let str = '';
for (const key in data) {
str += `${key}=${data[key]}&`;
}
return str.replace(/&$/, '');
}
}
使用说明
import IHttpUtils from '../../utils/IHttpUtils'
IHttpUtils.get({
url: 'https://www.apiopen.top/weatherApi?city=北京'
})
.then(res => console.log(res))
.catch(err => console.log(err);
IHttpUtils.post({
url: 'https://www.apiopen.top/satinApi',
data: {
type: 1,
page: 1
}
})
.then(res => {console.log(res))
.catch(err => console.log(err);
网友评论