美文网首页
axios 封闭http请求

axios 封闭http请求

作者: 如风_周 | 来源:发表于2018-06-29 15:43 被阅读36次

公司用react开发项目,特意封装了一个axios请求 代码如下:

import axios from 'axios'
/**
 * 基础配置
 * 更多配置请参考 https://github.com/axios/axios
 * @param {*} url  请求地址
 * @param {*} data  参数
 * @param {*} type  请求类型,默认post
 */

let HttpServer = async (url, data = {}, type = 'GET') => {
    let headers = {
        'content-type': 'application/x-www-form-urlencoded'
    };
    let config = {
        url: "http://192.168.0.157/"+url,
        method: type,
        params: data,
        timeout: 6000, // 超时时间
        headers: headers,
        responseType: 'json',
        validateStatus: function (status) {
            return status >= 200 && status < 300; // 默认的
        },
        maxRedirects: 5
    };
    let response = null;
    try {
        response = await axios(config);
        if(response.status == 200){
            if(response.data.code != "200"){
                alert(response.data.message);
                response = Promise.reject(response); 
            }
        }else if(response.status != 200){
            alert("服务器请求发生错误,请联系管理员");
        }
    } catch (error) {
        alert(error);
        response = Promise.reject(error);
    }
    return response;
};

export default HttpServer;

使用方式

httpServer("url",params).then(function(data){
  console.log(data)
});

相关文章

网友评论

      本文标题:axios 封闭http请求

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