zoukankan      html  css  js  c++  java
  • axios库的使用

    axios是基于Promise 用于浏览器和 nodejs 的 HTTP 客户端;可以用在webpack + vuejs 的项目中

    原文 https://github.com/axios/axios

    1、example

    1.1、get请求

    axios.get('/user?ID=12345')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    //换种方式
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    //从远程获取图片
    axios({
      method:'get',
      url:'http://bit.ly/2mTM3nY',
      responseType:'stream'
    })
      .then(function(response) {
      response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    });
    

    1.2、post请求

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    因axios post数据采用的是 Content-Type: 'application/x-www-form-urlencoded',所以后端是接受不到json格式的数据的
    解决方法:引入qs库,发送请求之前将数据qs.stringify(data),是为了将数据变成类似title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3这种格式

    1.2.1. application/x-www-form-urlencoded

    POST http://www.example.com HTTP/1.1
    Content-Type: application/x-www-form-urlencoded;charset=utf-8
    title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
    

    1.2.2 form-data

    POST http://www.example.com HTTP/1.1
    Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA
    ------WebKitFormBoundaryrGKCBY7qhFd3TrwA
    Content-Disposition: form-data; name="text"
    title
    ------WebKitFormBoundaryrGKCBY7qhFd3TrwA
    Content-Disposition: form-data; name="file"; filename="chrome.png"
    Content-Type: image/png
    PNG ... content of chrome.png ...
    ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
    

    1.2.3 application/json

    POST http://www.example.com HTTP/1.1
    Content-Type: application/json;charset=utf-8
    
    {"title":"test","sub":[1,2,3]}
    

    1.2.4 text/xml

    POST http://www.example.com HTTP/1.1
    Content-Type: text/xml
    
    <!--?xml version="1.0"?-->
    <methodcall>
        <methodname>examples.getStateName</methodname>
        <params>
            <param>
                <value><i4>41</i4></value>
            </param>
        </params>
    </methodcall>
    >
    

    1.3、并发请求

    function getUserAccount() {
      return axios.get('/user/12345');
    }
    
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function(acct, perms) {
        
      }));
    

    2 API

    2.1 发送请求配置config

    {
        url:'/user',
        method:`get`,
    
        //`baseURL`如果`url`不是绝对地址,那么将会加在其前面,当axios使用相对地址时这个设置非常方便
        baseURL:'http://some-domain.com/api/',
    
        //`transformRequest`允许请求的数据在传到服务器之前进行转化。
        //这个只适用于`PUT`,`GET`,`PATCH`方法。
        //数组中的最后一个函数必须返回一个字符串或者一个`ArrayBuffer`,或者`Stream`,`Buffer`实例,`ArrayBuffer`,`FormData`
        transformRequest:[function(data){
            //依自己的需求对请求数据进行处理
            return data;
        }],
    
        //`transformResponse`允许返回的数据传入then/catch之前进行处理
        transformResponse:[function(data){
            //依需要对数据进行处理
            return data;
        }],
    
        //`headers`是自定义的要被发送的头信息
        headers:{'X-Requested-with':'XMLHttpRequest'},
    
        //`params`是请求连接中的请求参数,必须是一个纯对象,或者URLSearchParams对象
        params:{
            ID:12345
        },
        
        //`paramsSerializer`是一个可选的函数,是用来序列化参数
        //例如:(https://ww.npmjs.com/package/qs,http://api.jquery.com/jquery.param/)
        paramsSerializer: function(params){
            return Qs.stringify(params,{arrayFormat:'brackets'})
        },
        data:{
            firstName:'fred'
        },
        //`timeout`定义请求的时间,单位是毫秒。
        //如果请求的时间超过这个设定时间,请求将会停止。
        timeout:1000,
        
        //`withCredentials`表明是否跨网站访问协议,
        //应该使用证书
        withCredentials:false //默认值
    
        //`adapter`适配器,允许自定义处理请求,这会使测试更简单。
        //返回一个promise,并且提供验证返回(查看[response docs](#response-api))
        adapter:function(config){
            /*...*/
        },
    
        //`auth`表明HTTP基础的认证应该被使用,并且提供证书。
        //这个会设置一个`authorization` 头(header),并且覆盖你在header设置的Authorization头信息。
        auth:{
            username:'janedoe',
            password:'s00pers3cret'
        },
    
        //`responsetype`表明服务器返回的数据类型,这些类型的设置应该是
        //'arraybuffer','blob','document','json','text',stream'
        responsetype:'json',
    
        //`xsrfHeaderName` 是http头(header)的名字,并且该头携带xsrf的值
        xrsfHeadername:'X-XSRF-TOKEN',//默认值
    
        //`onUploadProgress`允许处理上传过程的事件
        onUploadProgress: function(progressEvent){
            //本地过程事件发生时想做的事
        },
    
        //`onDownloadProgress`允许处理下载过程的事件
        onDownloadProgress: function(progressEvent){
            //下载过程中想做的事
        },
    
        //`maxContentLength` 定义http返回内容的最大容量
        maxContentLength: 2000,
    
        //`validateStatus` 定义promise的resolve和reject。
        //http返回状态码,如果`validateStatus`返回true(或者设置成null/undefined),promise将会接受;其他的promise将会拒绝。
        validateStatus: function(status){
            return status >= 200 && stauts < 300;//默认
        },
    
        //`httpAgent` 和 `httpsAgent`当产生一个http或者https请求时分别定义一个自定义的代理,在nodejs中。
        //这个允许设置一些选选个,像是`keepAlive`--这个在默认中是没有开启的。
        httpAgent: new http.Agent({keepAlive:treu}),
        httpsAgent: new https.Agent({keepAlive:true}),
    
        //`proxy`定义服务器的主机名字和端口号。
        //`auth`表明HTTP基本认证应该跟`proxy`相连接,并且提供证书。
        //这个将设置一个'Proxy-Authorization'头(header),覆盖原先自定义的。
        proxy:{
            host:127.0.0.1,
            port:9000,
            auth:{
                username:'cdd',
                password:'123456'
            }
        },
    
        //`cancelTaken` 定义一个取消,能够用来取消请求
        //(查看 下面的Cancellation 的详细部分)
        cancelToken: new CancelToken(function(cancel){
        })
    }
    
    //reponse 应该包括的内容
    {
      data: {},
      status: 200,
      statusText: 'OK',
      headers: {},
      config: {},
      request: {}
    }
    

    2.2 获取数据request方法

    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.options(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])

    2.3 拦截

    //发送request之前
    axios.interceptors.request.use(function (config) {
        return config;
      }, function (error) {
        return Promise.reject(error);
      });
    //对服务器数据处理
    axios.interceptors.response.use(function (response) {
        return response;
      }, function (error) {
        return Promise.reject(error);
      });
    
  • 相关阅读:
    在Netty使用中TLSv1.3
    基本路径测试
    测试准备
    skywalking源码中添加日志代码并打印
    Java应用启动集成skywalking
    Logback获取全局唯一标识 traceid记录到日志中
    通过示例展示Byte Buddy 如何增强 log() 方法
    SpringIOC
    Flask 信号机制
    Django 信号机制
  • 原文地址:https://www.cnblogs.com/yangwang12345/p/7808307.html
Copyright © 2011-2022 走看看