美文网首页
React中fetch简单及复杂请求的封装

React中fetch简单及复杂请求的封装

作者: Mr培 | 来源:发表于2020-01-02 10:19 被阅读0次

    1.请求的调用方式

    import React from "react";
    import {del, get} from "../../utils/ajax";
    class Index extends React.Component{
        componentDidMount() {
            this.get()
        }
        {--async await 解决请求异步问题--}
        get = async () => {
            {--参数以对象形式传入-}
            const res = await get('/banners', {
                page: 1,
                pageSize: 10
            });
            if (res.code !== 0) {
               //请求成功处理
            }
        };
    }
    export default Index;
    

    2.fetch请求的封装
    请求会带上cookies

    import { message } from 'antd'
    const BASE_URL = process.env.REACT_APP_BASE_URL || '';
    /**
     * 处理url
     * @param url
     * @param param
     * @returns {*}
     */
    function handleURL(url, param) {
        let completeUrl = '';
        if (url.match(/^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i)) {
            completeUrl = url
        } else {
            completeUrl = BASE_URL + url
        }
        if (param) {
            if (completeUrl.indexOf('?') === -1) {
                completeUrl = `${completeUrl}?${ObjToURLString(param)}`
            } else {
                completeUrl = `${completeUrl}&${ObjToURLString(param)}`
            }
        }
        return completeUrl
    }
    function handleUrl(url) {
        let completeUrl = '';
        if (url.match(/^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i)) {
            completeUrl = url
        } else {
            completeUrl = BASE_URL + url
        }
        return completeUrl
    }
    
    /**
     * 将参数对象转化为'test=1&test2=2'这种字符串形式
     * @param param
     * @returns {string}
     * @constructor
     */
    function ObjToURLString(param) {
        let str = '';
        if (Object.prototype.toString.call(param) === '[object Object]') {
            const list = Object.entries(param).map(item => {
                return `${item[0]}=${item[1]}`
            });
            str = list.join('&')
        }
        return str
    }
    //获取
    export async function get(url, param) {
        const completeUrl = handleURL(url, param);
        const response = await fetch(completeUrl, {
            credentials: 'include',
            xhrFields: {
                withCredentials: true       //跨域
            }
        });
        const reslut = await response.json();
        if (!response.ok) {
            if(response.status === 403){
                logout();
                history.push('/login')
            }
            message.error(reslut.message || '网络错误')
        }
        return reslut
    
    }
    
    //提交
    export async function post(url, param) {
        const completeUrl = handleUrl(url);
        const response = await fetch(completeUrl, {
            credentials: 'include',
            method: 'POST',
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(param)
        });
        const reslut = await response.json();
        if (!response.ok) {
            if(response.status === 403){
                logout();
                history.push('/login')
            }
            message.error(reslut.message || '网络错误')
        }
        return reslut
    }
    
    //patch修改
    export async function patch(url, param) {
        const completeUrl = handleUrl(url);
        const response = await fetch(completeUrl, {
            credentials: 'include',
            method: "PATCH",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(param)
        });
        const reslut = await response.json();
        if (!response.ok) {
            if(response.status === 403){
                logout();
                history.push('/login')
            }
            message.error(reslut.message || '网络错误')
        }
        return reslut
    }
    
    //put修改
    export async function put(url, param) {
        const completeUrl = handleUrl(url);
        const response = await fetch(completeUrl, {
            credentials: 'include',
            method: "PUT",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(param)
        });
        const reslut = await response.json();
        if (!response.ok) {
            if(response.status === 403){
                logout();
                history.push('/login')
            }
            message.error(reslut.message || '网络错误')
        }
        return reslut
    }
    
    
    //删除
    export async function del(url, param) {
        const completeUrl = handleURL(url, param);
        const response = await fetch(completeUrl, {
            credentials: 'include',
            method: 'delete',
            xhrFields: {
                withCredentials: true
            }
        });
        const reslut = await response.json();
        if (!response.ok) {
            if(response.status === 403){
                logout();
                history.push('/login')
            }
            message.error(reslut.message || '网络错误')
        }
        return reslut
    }
    

    3.BASE_URL全局参数的封装
    在根目录创建 .evn 文件

    REACT_APP_BASE_URL = http://localhost:3000/transfer_admin
    

    4.请求代理的设置
    在src目录创建 setupProxy.js 文件

    const proxy = require('http-proxy-middleware');
    
    module.exports = function (app) {
        app.use(
            proxy('/transfer_admin', {
                target: 'http://localhost:8081',
                changeOrigin: true
            }
        ))
    };
    

    相关文章

      网友评论

          本文标题:React中fetch简单及复杂请求的封装

          本文链接:https://www.haomeiwen.com/subject/uepnoctx.html