React中fetch簡單及複雜請求的封裝

React中fetch簡單及複雜請求的封裝

  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;
  1. 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
}
  1. BASE_URL全局參數的封裝
    在根目錄創建 .evn 文件
REACT_APP_BASE_URL = http://localhost:3000/transfer_admin
  1. 請求代理的設置
    在src目錄創建 setupProxy.js 文件
const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        proxy('/transfer_admin', {
            target: 'http://localhost:8081',
            changeOrigin: true
        }
    ))
};
發佈了30 篇原創文章 · 獲贊 26 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章