Fetch封装
import "whatwg-fetch";
import * as fetchJsonp from 'fetch-jsonp';
enum ContentType {
json = 'application/json;charset=UTF-8',
form = 'application/x-www-form-urlencoded; charset=UTF-8'
}
enum HttpMethod {
get = 'GET',
post = 'POST'
}
interface IHeader {
Accept?: string;
'Content-Type': string;
[propName: string]: any;
}
interface IReqConfig {
method?: string;
credentials?: string;
headers?: IHeader;
body?:any;
}
interface IHttp {
getFetch<R,P={}>(url: string, params?:P, options?:RequestInit): Promise<R>;
postFetch<R,P={}>(url: string, params?:P): Promise<R>;
}
export default class HttpRequests implements IHttp {
public handleUrl = (url: string) => (params:any):string => {
if(params){
let paramsArray = [];
Object.keys(params).forEach((key) =>
paramsArray.push(key + "=" + encodeURIComponent(params[key]))
);
if (url.search(/\?/) === -1) {
typeof params === "object" ? (url += "?" + paramsArray.join("&")) : url;
} else {
url += "&" + paramsArray.join("&");
}
}
return url;
}
public async getFetch<R, P={}>(url: string, params?:P, options?:RequestInit):Promise<R>{
options = {
method: HttpMethod.get,
credentials: 'include',
headers: {
'Content-Type': ContentType.json
}
}
return await fetch(this.handleUrl(url)(params), options)
.then<R>((response) => {
if (response.ok) {
return response.json();
} else {
}
})
.then<R>((response) => {
if (response) {
return response;
} else {
return response;
}
})
.catch<R>((error) => {
return error;
});
}
public async postFetch<R, P={}>(url: string, params?: P):Promise<R> {
let formData = new FormData();
Object.keys(params).forEach((key) => formData.append(key, params[key]));
let options: RequestInit = {
method: HttpMethod.get,
credentials: 'include',
headers: {
'Content-Type': ContentType.json
},
body: formData
}
return await fetch(url, options)
.then<R>((response) => {
if (response.ok) {
return response.json();
} else {
}
})
.then<R>((response) => {
return response;
})
.catch<R>((error) => {
return error;
});
}
}
使用
import HttpReq from './request';
const Http = new HttpReq();
export async function getFetch(url:string, params:any) {
return Http.getFetch(url, params);
}
export async function postFetch(url:string, params:any) {
return Http.postFetch(url, params);
}