vue中封装axios请求

最近接手新的vue项目,发现axios竟然没有封装,立马动手封装,这里记录一下完整的封装过程,废话不说,直接上代码
baseConfig.js文件

//存放各个服务器的地址
// const express = require('express')
const proEnv = require('./pro.env')  // 生产环境配置文件,这里给出一个示例,其他都相似
const uatEnv = require('./uat.env')  // 测试环境
const devEnv = require('./dev.env')  // 本地环境
// const app = express()
const env = process.env.NODE_ENV;
console.log("env",env)
let target = '';
if (env === 'development') {
    target = devEnv.hosturl
} else if (env === 'production') {
    target = proEnv.hosturl
} else {
    target = uatEnv.hosturl
}
// module.exports =  target
export default target;

pro.env文件

// 生产环境
const hosturl = 'http://xx.xx.xx.xxx:xx'
module.exports = {
  NODE_ENV: 'production',
  hosturl: hosturl
}

在src/api下新建一个httplib.js来放封装内容

import axios from 'axios'
import {
    stringify
} from "qs";
// 引入上述文件
import target from "../config/baseConfig.js";

/*
* 封装axios  2020.4.7 --by lhg
*/
const codeMessage = {
    200: "服务器成功返回请求的数据。",
    201: "新建或修改数据成功。",
    202: "一个请求已经进入后台排队(异步任务)。",
    204: "删除数据成功。",
    400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。",
    401: "用户没有权限(令牌、用户名、密码错误)。",
    403: "用户得到授权,但是访问是被禁止的。",
    404: "发出的请求针对的是不存在的记录,服务器没有进行操作。",
    406: "请求的格式不可得。",
    408: "请求失败了",
    410: "请求的资源被永久删除,且不会再得到的。",
    422: "当创建一个对象时,发生一个验证错误。",
    500: "服务器发生错误,请检查服务器。",
    502: "网关错误。",
    503: "服务不可用,服务器暂时过载或维护。",
    504: "网关超时。"
};
const getFullUrl = (url) => {
    if (url.indexOf("http://") != -1 || url.indexOf("https://") != -1) {
        return url;
    }
    let newUrl = target + url;
    return newUrl;
}
//todo:暂时不了解返回数据结构,可根据自己项目的返回数据格式进行编写   2020.4.7
// const checkStatus = response => {
//     // console.log("checkStatus respone = ", response);
//     // if (response.status >= 200 && response.status < 300) {
//     //   // token失效处理
//     //   if (response.data && response.data.result == 9 ||response.data.result == 104 || response.data.result == 105 || response.data.result == 1007) {
//     //     store.dispatch('user/resetToken').then(() => {
//     //       setTimeout(() => {
//     //         location.reload();
//     //       }, 1000);
//     //     });
//     //   }
//     //   return response;
//     // }
//     const errortext = codeMessage[response.status] || response.statusText;
//     const error = new Error(errortext);
//     error.name = response.status;
//     error.response = response;
//     throw error;
// };

/**
 * 执行 post 请求, 请求体为 JSON
 * @param {JSON} requestConfig 请求参数
 * {
 *    url:"/view/a/b/xxxxx",
 *    params: {
 *      var1:"var1"
 *      ...
 *    },
 *    headers: {}, // headers
 *    timeout: 15000, //超时时长,单位毫秒
 *    config:{  // axios config
 *      ...
 *    }
 * }
 */
export function postJson(requestConfig) {
    // console.log("postForm , body = ", requestConfig.params);
    const options = {
        url: getFullUrl(requestConfig.url),
        method: "post",
        data: requestConfig.params, //将对象转换为JSON字符串
        headers: requestConfig.headers || {
            "Content-Type": "application/json; charset=utf-8"
        },
    };
    // alert(JSON.stringify(options));
    return request(options);
}

/**
 * 执行 post from表单 请求, 请求方式为 form 表单提交
 * @param {JSON} requestConfig 请求参数
 *
 */
export function postForm(requestConfig) {
    console.debug("调用 postForm , url = ", getFullUrl(requestConfig.url));
    const dataParams = stringify(requestConfig.params); //将对象转换为 key1=val1&key2=val2 格式
    // console.debug("body, data = ", dataParams);
    const options = {
        method: "post",
        data: dataParams,
        headers: requestConfig.headers || {
            Accept: "application/json",
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
        },
        url: getFullUrl(requestConfig.url),
    };
    return request(options);
}

/**
 * 执行 get 请求
 * @param {JSON} requestConfig 请求参数
 *
 */
export function get(requestConfig) {
    const options = {
        method: "get",
        headers: requestConfig.headers || {
            Accept: "application/json"
            // "Content-Type": "application/json"
        },
        params: requestConfig.params,
        url: getFullUrl(requestConfig.url),
        // timeout: requestConfig.timeout || 15000
    };
    return request(options);
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {object} [option] The options we want to pass to "axios.request"
 * @return {object}           An object containing either "data" or "err"
 */
export function     request(option) {
    // console.log(option);
    // console.log("request url = %s,  params = %o", option.url, option.data);
    const options = {
        ...option
    };
    const defaultOptions = {
        // credentials: 'include',
        timeout: 15000
    };
    const newOptions = {
        ...defaultOptions,
        ...options
    };
    return (
        axios
            .request(newOptions)
            // .then(checkStatus)
            .then(response => {
                // alert(response)
                console.log('response:', response);
                return response.data;
            // }).then(response => {
            //     return response;
            }).catch(error => {
            console.log("request error = ", error);
            if (error.response) {
                // The request was made and the server responded with a status code
                // that falls out of the range of 2xx
                console.log("error.response.data = ", error.response.data);
                console.log("error.response.status = ", error.response.status);
                console.log("error.response.headers = ", error.response.headers);
            } else if (error.request) {
                // The request was made but no response was received
                // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                // http.ClientRequest in node.js
                console.log("error.request = ", error.request);
            } else {
                // Something happened in setting up the request that triggered an Error
                console.log("error.message = ", error.message);
            }
            console.log("error.config = ", error.config);
        })
    );
}

至此,封装完成,下面是在组件中调用示例
在src/api下面统一管理接口,可根据不同的组件建立文件夹

import {get, postForm, postJson} from '../httplib'

//测试axios封装
export function test_axios() {
    return postJson({
        params: {
            "account": "254745674567",
            "password": "976e3af6173e0939c642ea003e4cb956",
            "platform": 3,
            "device": {
                "udid": "254745674567"
            }
        },
        url: "/api/center/login"
    })
}

在组件中调用





最后,记录一个小问题,小伙伴们要注意module.exports、require和export default、import要配对使用哦,不可混用,因为之前代码遗留为module.exports,而我使用import导入,所以一直报错

你可能感兴趣的:(vue,前端)