加载中...
  • axios使用方法

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

    • 从浏览器中创建 XMLHttpRequests
    • 从 node.js 创建 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求数据和响应数据
    • 取消请求
    • 自动转换 JSON 数据
    • 客户端支持防御 XSRF

    安装

    使用npm安装

    1
    npm install axios

    使用 bower安装

    1
    bower install axios

    使用 cdn:

    1
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    例子:

    vue中全局使用

    1.结合 vue-axios使用

    看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了
    首先在主入口文件main.js中引用:
    1
    2
    3
    4
    import axios from 'axios'
    import VueAxios from 'vue-axios'

    Vue.use(VueAxios,axios);
    之后就可以使用了,在组件文件中的methods里去使用了:
    1
    2
    3
    4
    5
    6
    7
    getNewsList(){
    this.axios.get('api/getNewsList').then((response)=>{
    this.newsList=response.data.data;
    }).catch((response)=>{
    console.log(response);
    })
    }

    2.axios 改写为 Vue 的原型属性

    首先在主入口文件main.js中引用,之后挂在vue的原型链上:
    1
    2
    import axios from 'axios'
    Vue.prototype.$ajax= axios
    在组件中使用:
    1
    2
    3
    4
    5
    6
    this.$ajax.get('api/getNewsList')
    .then((response)=>{
    this.newsList=response.data.data;
    }).catch((response)=>{
    console.log(response);
    })

    局部使用

    直接引入
    1
    import axios from 'axios'
    然后就可以直接用了

    常用的配置项初始化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    //  常规配置项
    axios.defaults.baseURL = 'https://127.0.0.1:9999'; // 请求服务器具体的地址
    axios.defaults.withCredentials =true; // 在跨域中允许携带凭证
    axios.defaults.header['Content-Type'] = 'application/x-www-form-urlencoded';// 声明传给服务器的数据,通过请求传给服务器的数据application/x-www-form-urlencoded格式
    axios.defaults.headers.common["token"] = token; // 携带token请求头

    // 请求拦截器:当我们通过porps请求向服务器发请求的时候,能拦截到请求主体信息,然后把请求主体传递进来的json格式的对象,变成urlencoded 某某某等于&某某某格式发送给服务器
    axios.defaults.transformRequest = function (data) {
    if (data) return data;
    let result = ``;
    for (let attr in data) {2
    if(!data.hasOwnProperty(attr)) break;
    result += `&${attr}=${data[attr]}`;
    }
    return result.substring(1);
    };
    // 响应服务器:接受服务器返回的结果,把返回的结果,因为它的anshuosi从服务器获得的结果response对象当中包含了很多信息,既有响应头也有相应主体的信息,xx配置信息。
    // 现在只拿到data,如果有错误就抛出错误的Promise,
    axios.interceptor.response.use(function onFultfilled(response) {
    // 成功走这个
    return response.data;
    }, function onRejected(reason) {
    // 失败走这个
    return Promise.reject(reason);
    });
    // 验证什么时候成功失败,用正则检验,自定义成功失败,主要以http状态码
    axios.dafaults.validateStatus = function (status) {
    // http状态码,2或者3开头的都是成功,默认只有2开头的才能成功
    return /^(2\3)\d{2}$/.test(status);
    }

    使用方式示例

    1.执行get数据请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    axios.get('url',{
    params:{
    id:'接口配置参数(相当于url?id=xxxx)'
    },
    })
    .then((res)=>{
    console.log(res); // 处理成功的函数 相当于success
    })
    .catch((error)=>{
    console.log(error) // 错误处理 相当于error
    })

    2.执行post数据发送

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    const data = {
    name:'张三',
    age:23
    }
    axios.post('url',data)
    .then((res)=>{
    console.log(res); // 处理成功的函数 相当于success
    })
    .catch((error)=>{
    console.log(error) // 错误处理 相当于error
    })

    3.执行delete 数据发送

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    //  如果服务端将参数作为java对象来封装接受
    axios.delete('demo/url', {
    data: {
    id: 123,
    name: 'Henry',
    },
    timeout: 1000,
    })
    // 如果服务端将参数作为url参数来接受,则请求的url为:www.demo/url?a=1&b=2形式
    axios.delete('demo/url', {
    params: {
    id: 123,
    name: 'Henry',
    },
    timeout: 1000
    })

    4.执行put 数据发送

    1
    2
    3
    4
    5
    6
    axios.put('demo/url', {
    id: 123,
    name: 'Henry',
    sex: 1,
    phone: 13333333
    })

    5.携带请求头
    axios设置请求头中的Authorization信息:
    GET请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    this.$axios.get('/url', 
    {
    headers: {
    'Authorization': 'Bearer '+localStorage.getItem('token'),
    'token': ' '
    ...
    },
    params: {
    param1: string,
    param2: string
    },
    ...
    }
    )
    .then(res => fn)
    .catch(err => fn)
    上一篇:
    AES加密解密的使用方法
    下一篇:
    vue3.0 vue.config.js 配置
    本文目录
    本文目录