axios encapsulates http requests, implements get, post (json format), postForm (form submission) methods

In the process of our project development, interaction with the background is inseparable, that is, we often say that the interface is out of the jquery development system, axios stands out in the development of our framework vue, react, etc. The following code example works Requests encapsulated by themselves.


import axios from 'axios';
import { message } from 'antd';
import qs from 'qs';
import config from '@config/config';
import React from 'react';

const request = {};
message.config({
    duration: 2,
    maxCount: 1
});

const next = (cb) => {
    return (res) => {
        if ((res.status >= 200 && res.status < 300) && res.data && res.data.success) {
            if (res.data.message) {
                message.success(<span className='comment'>{res.data.message}</span>);
            }
            cb(res.data);
        } else {
            cb(res.data);
            if (res.data.message) {
                message.error(<span className='comment'>{res.data.message}</span>);
            }
        }
    };
};

const error = () => (e) => {
    message.error(<span className='comment'>{e.message}</span>);
};

request.get = (url, params, cb)=>{
    url = config.server + url;
    axios.get(url, {params: params})
        .then(next(cb))
        .catch(error());
};

request.post = (url, data, cb)=>{
    url = config.server + url;
    axios.post(url, data, {})
        .then(next(cb))
        .catch(error());
};

// 适用于Content-Type'为'application/x-www-form-urlencoded post请求
request.postForm = (url, data, cb,)=>{
    url = config.server + url;
    const header = {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}};
    axios.post(url, qs.stringify(data), header)
        .then(next(cb))
        .catch(error());
};

export default request;

Please correct me if there is an error! ! ! !

Published 9 original articles · won 34 · views 3684

Guess you like

Origin blog.csdn.net/m0_37685031/article/details/105490434