码迷,mamicode.com
首页 > 移动开发 > 详细

axios

时间:2019-09-04 19:15:00      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:mss   formdata   tab   format   message   fine   err   date   ati   

  axios 是基于原生的ES6 Promise 实现,如果浏览器环境不支持请使用垫片。

1.特征

  • 浏览器端发起XMLHttpRequests请求

  • node端发起http请求

  • 支持Promise API

  • 拦截请求和返回

  • 转化请求和返回数据

  • 取消请求

  • 自动转化json数据

  • 客户端支持抵御XSRF(跨站请求伪造)

  axios.get(‘/user‘, {
      params: {
        ID: 12345
      }
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    })
    .then(function () {
 
    });  

  对axios传递一些的设置来生成请求。

  axios({
    method: ‘post‘,
    url: ‘/user/12345‘,
    data: {
      firstName: ‘Fred‘,
      lastName: ‘Flintstone‘
    }
  });

  注意:使用别名方法时url,不需要在config中指定methoddata属性。

 请求方法:

  • 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]]) 

并发

  • axios.all(iterable)

  • axios.spread(callback)

 注意:因为axios.all使用的是类似Primise.all的功能,所以如果其中有一个请求出现了错误那么就会停止请求,所以建议对于单个请求最好附加上处理的catch。

 

2.请求设置

 请求时的设置选项。只有 url 是必须的,如果没有指明 method 的话,默认的请求方法是 GET.

  {
      // url 是服务器链接,用来请求
      url:‘/user‘,
?
      // method 是发起请求时的方法
      method:`get`,
?
      // baseURL如果 url 不是绝对地址,那么将会加在其前面。
      // 可以很方便的对相对地址的axios实例设置 baseUrl 。
      baseURL:‘http://some-domain.com/api/‘,
?
      // transformRequest 允许请求的数据在发送至服务器之前进行转化。
      // 这个只适用于 PUT , POST , PATCH 方法。
      // 数组中的最后一个函数必须返回一个字符串或者一个 ArrayBuffer ,或者 Stream , Buffer 实例,  ArrayBuffer , FormData 
      //此外你也可能需要设置下headers对象
      transformRequest:[function(data,headers){
          return data;
      }],
?
      // transformResponse 允许对返回的数据传入then/catch之前进行处理
      transformResponse:[function(data){
          return data;
      }],
?  
      // headers 是自定义的要被发送的信息头
      headers:{‘X-Requested-with‘:‘XMLHttpRequest‘},
?
      // params 是请求连接中的请求参数,必须是一个纯对象,或者URLSearchParams对象
      params:{
          ID:12345
      },
    
      // paramsSerializer 是一个可选的函数,用来控制和序列化参数
      paramsSerializer: function(params){
          return Qs.stringify(params,{arrayFormat:‘brackets‘})
      },
?
      // data 是请求时作为请求体的数据
      data:{
          firstName:‘fred‘
      },
      //`timeout`定义请求的时间,单位是毫秒。
      //如果请求的时间超过这个设定时间,请求将会停止。
      timeout:1000,
    
      //`withCredentials`表明跨域请求书否需要证明。
      withCredentials:false //默认值
?
      // adapter 适配器,允许自定义处理请求,这会使测试更简单。
      //返回一个promise,并且提供一个有效的响应。
      adapter:function(config){
          /*...*/
      },
?
      // auth 表明HTTP基础的认证应该被使用,并且提供证书。
      //这个会设置一个 authorization头,并且覆盖你在header设置的 Authorization头信息。
      auth:{
          username:‘janedoe‘,
          password:‘s00pers3cret‘
      },
?
      // responsetype 表明服务器返回的数据类型,这些类型的设置应该是
      //‘arraybuffer‘,‘blob‘,‘document‘,‘json‘,‘text‘,stream‘
      responsetype:‘json‘,
?
      // responseEncoding 表明解析相应的编码方式。
      // 注意:会忽视responseType为stream或者客户端的请求。
      responseEncoding:‘utf8‘ //默认值
?
      // xsrfCookieName 时cookie做xsrf会话时的名字。
      xsrfCookieName:‘XSRF-TOKEN‘, //默认值
?
      // xsrfHeaderName 是http头的名字,并且该头携带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将会resolve;其他的promise将reject。
      validateStatus: function(status){
          return status >= 200 && stauts < 300; //默认
      },
?
      // maxRedirect 定义重导向到node.js中的最大数量。
    //如果值为0,那么没有redirect。
      maxREdirects:5, //默认值
?
      // socketPath 定义一个在node.js中使用的 UNIX Socket。
      // 例如: /var/run/docker.sock 发送请求到 docker daemon。
      // socketPath 和 proxy 只可定义其一,如果都定义则只会使用 socketPath 。
      socketPath:null, //默认值
?
      // httpAgent 和 httpsAgent 当产生一个http或者https请求时分别定义一个自定义的代理,
      //在nodejs中,这个允许设置一些类似 keepAlive 的选项,这个在默认中是没有开启的。
      httpAgent: new http.Agent({keepAlive:true}),
      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‘
          }
      },
?  
      // cancelToken  定义一个取消,能够用来取消请求
      cancelToken: new CancelToken(function(cancel){
      })
  }

 

3.返回响应信息

 一个请求的返回包含以下信息

{
    //`data`是服务器的提供的回复(相对于请求)
    data{},
?
    //`status`是服务器返回的http状态码
    status:200,
?
?
    //`statusText`是服务器返回的http状态信息
    statusText: ‘ok‘,
?
    //`headers`是服务器返回中携带的headers
    headers:{},
?
    //`config`是对axios进行的设置,目的是为了请求(request)
    config:{}
?
    //`request`是获取当前相应的请求,是在浏览器中的XMLHttpREquest实例
}
使用 then 时,会接受到下面的信息:

axios.get(‘/user/12345‘)
    .then(function(response){
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
    });

 

4.设置默认设置

  设置默认的设置,这设置将在之后的每次请求中生效。

  全局默认设置

  axios.defaults.baseURL = ‘https://api.example.com‘;
  axios.defaults.headers.common[‘Authorization‘] = AUTH_TOKEN;
  axios.defaults.headers.post[‘Content-Type‘]=‘application/x-www-form-urlencoded‘;

  实例中自定义默认值

  //当创建一个实例时进行默认设置
  var instance = axios.create({
      baseURL:‘https://api.example.com‘
  });
?
  //或者在实例创建之后改变默认值
  instance.defaults.headers.common[‘Authorization‘] = AUTH_TOKEN;

 

5.拦截器 interceptors

  在请求或者返回被 then 或者 catch 处理之前对他们进行拦截。

  //添加一个请求拦截器
  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);
    });

  移除拦截器

   var myInterceptor = axios.interceptors.request.use(function(){/*...*/});
    axios.interceptors.request.eject(myInterceptor);

  在一个axios实例中使用拦截器

    var instance = axios.create();
    instance.interceptors.request.use(function(){/*...*/});

 

6.取消请求

  cancel token取消一个请求

  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();

  axios.get(‘/user/12345‘, {
    cancelToken: source.token
  }).catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log(‘Request canceled‘, thrown.message);
    } else {
      // handle error
    }
  });

  axios.post(‘/user/12345‘, {
    name: ‘new name‘
  }, {
    cancelToken: source.token
  })

  source.cancel(‘Operation canceled by the user.‘);

 

7.使用 application/x-www-form-urlencoded 格式的方式

  默认情况下,axios串联js对象为JSON格式。为了发送application/x-wwww-form-urlencoded格式数据,有以下方法:

  1. 在浏览器中使用URLSearchParams API:

    注意:URLSearchParams不支持所有的浏览器,但是这里有个垫片可用(确保垫片在浏览器全局环境中)

  var params = new URLSearchParams();
  params.append(‘param1‘,‘value1‘);
  params.append(‘param2‘,‘value2‘);
  axios.post(‘/foo‘,params);

  2.1 可以使用qs库来对数据编码。

       注意:qs 如果您需要对嵌套对象进行字符串化,那么该库是首选

  var qs = require(‘qs‘);
  axios.post(‘/foo‘, qs.stringify({‘bar‘:123}));

  2.2 使用qs库的另一种方式(es6)

  import qs from ‘qs‘;
  const data = {‘bar‘:123};
  const options = {
    method:‘POST‘,
    headers:{
      ‘content-type‘:‘application/x-www-from-urlencoded‘
    },
    data:qs.stringify(data),
    url
  }
  axios(options)

axios

标签:mss   formdata   tab   format   message   fine   err   date   ati   

原文地址:https://www.cnblogs.com/yaokai729/p/11460834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!