axios相关使用

一、axios安装

使用npm安装axios
    npm install axios
使用cnpm安装axios
    cnpm install axios
使用yarn安装axios
    yarn install axios
使用cdn链接
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、请求数据方法

  • get请求:方式一:
    axios({
        // 默认请求方式为get
        method: 'get',
        url: 'api',
        // 传递参数
        params: {
            key: value
        },
        // 设置请求头信息
        headers: {
            key: value
        }
        responseType: 'json'
    }) then(response => {
        // 请求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 请求失败,
        console.log(error);
    });
  • get请求:方式二
    axios.get("api", {
        // 传递参数
        params: {
            key: value
        },
        // 设置请求头信息,可以传递空值
        headers: {
            key: value
        }
    }) then(response => {
        // 请求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 请求失败,
        console.log(error);
    });
  • post请求:方式一
    // 注:post请求方法有的要求参数格式为formdata格式,此时需要借助 Qs.stringify()方法将对象转换为字符串
    let obj = qs.stringify({
        key: value
    });

    axios({
        method: 'post',
        url: 'api',
        // 传递参数
        data: obj,
        // 设置请求头信息
        headers: {
            key: value
        }
        responseType: 'json'
    }) then(response => {
        // 请求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 请求失败,
        console.log(error);
    });
  • post请求:方式二
    let data = {
            key: value
        },
        headers = {
            USERID: "",
            TOKEN: ""
        };
    // 若无headers信息时,可传空对象占用参数位置
    axios.post("api", qs.stringify(data), {
        headers
    }
    }) then(response => {
        // 请求成功
        let res = response.data;
        console.log(res);
    }).catch(error => {
        // 请求失败,
        console.log(error);
    });
  • Qs的使用
    • 引用cdn或者使用npmcnpm或者yarn进行插件安装
    • 使用cdn时,默认全局变量为Qs
    • Qs基本方法使用
      • qs.stringify() 方法:将目标数据转换为string字符串
      • qs.parse() 方法:将对象字符串格式的数据转换为对象格式
01-20 01:34