AlexZ33 / lessions

自己练习的各种demo和课程
12 stars 2 forks source link

fetch封装 #43

Open AlexZ33 opened 5 years ago

AlexZ33 commented 5 years ago

import { notification, message } from 'antd';
import { codeMessage } from './common/mapping';
import Config from './common/config';
import fetch from 'dva/fetch';

const SERVER = Config.backendServer;

// 后端返回数据
// { code: 操作状态, message: 消息提示, data: 返回的数据 }
// code=0 请求成功,code=-1 请求失败,code=-2 请求警告

// 检测响应内容
// 20x将返回响应内容,非20x生成错误并抛出
function checkRequest(resp) {
    if (resp.status >= 200 && resp.status < 300) {
        return resp;
    };
    const error = new Error(codeMessage[resp.status] || resp.statusText);
    error.name = resp.status;
    error.response = resp;
    throw error;
};

// 对HTTP请求统一封装
function request(url, options) {
    const newOptions = {
        ...options,
        credentials: 'include',
    };

    if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
        newOptions.headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=utf-8',
        };
        newOptions.body = JSON.stringify(newOptions.body);
    };

    return fetch(url, newOptions).then(checkRequest).then(resp => {
        return resp.json();
    }).then(resp => {
        if (resp.code < 0) {
            let arr = resp.message.split('\n')

            if (arr.length === 0) {
                message.error(resp.message);
            } else {
                arr.map((s) => {
                    message.error(s.trim());
                    return null;
                });
            };
            // message不为空时根据code值返回提示/警告消息 
        } else if (resp.message !== "") {
            if (resp.code === 0) {
                message.success(resp.message);
            };
            if (resp.code === -2) {
                message.warn(resp.message);
            };
        };
        return resp.data;
    }).catch(err => {
        notification.error({
            message: `请求错误 ${err.name}: ${err.response.url}`,
            description: err.message,
        });
    });
};

// 请求后端获取导航数据
export function getMenu() {
    return request(`${SERVER}/api/v1/menu`, {
        method: 'GET',
    });
};

// WEBPACK FOOTER //
// ./src/components/BeehiveHeader/request.js

export const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队(异步任务)。',
    204: '删除数据成功。',
    400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限(令牌、用户名、密码错误)。',
    403: '用户得到授权,但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除,且不会再得到的。',
    422: '当创建一个对象时,发生一个验证错误。',
    500: '服务器发生错误,请检查服务器。',
    502: '网关错误。',
    503: '服务不可用,服务器暂时过载或维护。',
    504: '网关超时。',
};