TypeScript Fetch封装使用

摘要:Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源

Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。 这种功能以前是使用 XMLHttpRequest实现的。Fetch提供了一个更好的替代方法,可以很容易地被其他技术使用,例如 Service Workers。Fetch还提供了单个逻辑位置来定义其他HTTP相关概念,例如CORS和HTTP的扩展。


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("服务器繁忙,请稍后再试;\
\
Code:" + 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);
}

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_4687