美文网首页
2020-01-11 axios的基本使用

2020-01-11 axios的基本使用

作者: 反复练习的阿离很笨吧 | 来源:发表于2020-01-11 23:17 被阅读0次

    axios的基本使用

    安装axios,因为运行时也要用到所以是--save
    npm install axios --save

    axios支持多种请求方式:
    axios(config)
    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])

    发送get请求演示

    在任意的js文件中都可以用

    import axios from 'axios'
    axios({
    })
    //传入config对象
    

    例如:

    axios({
      url: 'lalalala/home/multidata'
    }).then(res=>{
      console.log(res);
    })
    

    axios返回的是promise对象,可以直接调用then方法,获得请求到的数据。

    axios发送并发请求

    有时候, 我们可能需求同时发送两个请求
    使用axios.all, 可以放入多个请求的数组.
    axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

    同时请求完多个url再返回:

    axios.all([axios({
            url: 'http://lalalala/home/multidata'
        }
    ), axios({
        url: 'http://lalalala/home/multidata',
        params: {
            type: 'sell',
            page: 5
        }
    })]).then(res => {
        console.log(res);
    }))
    

    第二个请求的res是一个数组:

    (2) [{…}, {…}]
    0: {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
    1: {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
    length: 2
    __proto__: Array(0)
    

    axios.spread()方法

    axios.all([axios({
            url: 'http://lalalala/home/multidata'
        }
    ), axios({
        url: 'http://lalalala/home/multidata',
        params: {
            type: 'sell',
            page: 5
        }
    })]).then(axios.spread((res1, res2) => {
        console.log(res1);
        console.log(res2);
    }))
    

    log出

    Object
    data: {data: {…}, returnCode: "SUCCESS", success: true}
    status: 200
    statusText: "OK"
    headers: {content-length: "4605", content-type: "application/json"}
    config: {url: "http://lalala", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
    request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
    __proto__: Object
    

    全局配置

    在开发中可能很多参数都是固定的.
    这个时候我们可以进行一些抽取, 也可以利用axiox的全局配置

    axios.defaults.baseURL = ‘lalalala:8000’�
    axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
    

    例如:

    axios.defaults.baseURL='http://lalalala:8000'
    axios.defaults.timeout=5000
    
    axios.all([axios({
            url: 'http://lalalala:8000/home/multidata'
        }
    ), axios({
        url: 'http://lalalala:8000/api/hy/home/multidata',
        params: {
            type: 'sell',
            page: 5
        }
    })]).then(res => {
      console.log(res);
    })
    

    常见配置:
    请求地址
    url: '/user',
    请求类型
    method: 'get',
    请根路径
    baseURL: 'http://www.mt.com/api',
    请求前的数据处理
    transformRequest:[function(data){}],
    请求后的数据处理
    transformResponse: [function(data){}],
    自定义的请求头
    headers:{'x-Requested-With':'XMLHttpRequest'},
    URL查询对象
    params:{ id: 12 },
    查询对象序列化函数
    paramsSerializer: function(params){ }
    request body
    data: { key: 'aa'},
    超时设置s
    timeout: 1000,
    跨域是否带Token
    withCredentials: false,
    自定义请求处理
    adapter: function(resolve, reject, config){},
    身份验证信息
    auth: { uname: '', pwd: '12'},
    响应的数据格式 json / blob /document /arraybuffer / text / stream
    responseType: 'json',

    axios的实例

    当我们从axios模块中导入对象时, 使用的实例是默认的实例.
    当给该实例设置一些默认配置时, 这些配置就被固定下来了.
    但是后续开发中, 某些配置可能会不太一样.
    比如某些请求需要使用特定的baseURL或者timeout或者content-Type等.
    这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.

    每一个实例都有独立的配置

    // 创建对应的axios实例
    const instance1 = axios.create({
        baseURL: 'http://lalalala:8000',
        timeout: 5000
    })
    
    const instance2 = axios.create({
        baseURL: 'http://lalaland:8000/',
        timeout: 5000
    })
    
    instance1({
        url: '/home/multidata'
    }).then(res => {
        console.log(res);
    })
    
    instance2({
        url: '/home/data',
        params: {
            type: 'sell',
            page: 5
        }
    }).then(res => {
        console.log(res);
    })
    

    axios封装

    如果不封装起来,在每个组件中都import axios,一个页面有无数个组件,如果要换依赖,每个都要一个一个改会很麻烦。
    因此不要在每个组件里面对第三方有依赖!最好是自己封装一个,每次都调自己的。

    新建network文件夹,放关于网络层的东西。
    request.js

    axios提供的拦截器

    拦截器用于我们在发送每次请求或者得到相应后,进行对应的处理。

    1. 请求拦截request
      请求拦截中错误拦截较少,通常都是配置相关的拦截
      可能的错误比如请求超时,可以将页面跳转到一个错误页面中。
    2. 响应拦截
      响应拦截中完成的事情:
      响应的成功拦截中,主要是对数据进行过滤。
      响应的失败拦截中,可以根据status判断报错的错误码,跳转到不同的错误提示页面。

    拦截之后记得return

    这就是传说中的aop?

    相关文章

      网友评论

          本文标题:2020-01-11 axios的基本使用

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