Fetch封裝
import "whatwg-fetch";
// import { fetchJsonp } from 'fetch-jsonp';
import * as fetchJsonp from 'fetch-jsonp';
/**
* @description: 枚舉出請求數據格式類型
* @param {type} 枚舉類型
* @return:
*/
enum ContentType {
json = 'application/json;charset=UTF-8',
form = 'application/x-www-form-urlencoded; charset=UTF-8'
}
/**
* @description: 枚舉request請求的method方法
* @param {type} 枚舉類型
* @return:
*/
enum HttpMethod {
get = 'GET',
post = 'POST'
}
/**
* @description: 聲明請求頭header的類型
* @param {type}
* @return:
*/
interface IHeader {
Accept?: string;
'Content-Type': string;
[propName: string]: any;
}
/**
* @description: 聲明fetch請求參數配置
* @param {type}
* @return:
*/
interface IReqConfig {
method?: string;
credentials?: string;
headers?: IHeader;
body?:any;
}
interface IHttp {
getFetch<R,P={}>(url: string, params?:P, options?:RequestInit): Promise<R>;
// getFetchJsonp<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 {
// alert("服務器繁忙,請稍後再試!");
}
})
.then<R>((response) => {
// response.code:是與服務器端約定code:200表示請求成功,非200表示請求失敗,message:請求失敗內容
if (response) {
return response;
} else {
// 非 200,錯誤處理
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 {
// alert("服務器繁忙,請稍後再試;\r\nCode:" + response.status);
}
})
.then<R>((response) => {
// response.code:是與服務器端約定code:200表示請求成功,非200表示請求失敗,message:請求失敗內容
return response;
})
.catch<R>((error) => {
// alert("當前網絡不可用,請檢查網絡設置!");
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);
}