Axios学习

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

Axios特点: 

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

axios API

1. 通过向axios传递相关配置来创建请求

  • axios( url , [config] )     
    axios( '/user/12345');   // 发送GET请求(默认的方法)
  • axios(config)          
    axios( {
       methods: 'post' ,  // 发送POST请求
       url: '/user/12345',
       data: {
           firstName:'Fred',
           lastName: 'Flintstone'
       }
    });

     

2. 请求方法的别名

 为方便起见,为所有支持的请求方法提供了别名。

  • axios.request( config )
  • axios.get( url , [config] )
    axios.get ('/user?ID=12345')     // axios 发送GET请求
       .then( function(res){
           console.log( response);
       } )
       .catch( function(error){
           console.log( error );
       } ); 
  • axios.head( url , [config] )
  • axios.delete( url, [config] )
  • axios.put( url , [data], [config] )
  • axios.post( url , [data], [config] )
    axios.post ('/user', { firstName:"Fred", lastName:"Flintstone" })    // axios发送POST请求
      .then( function(res){ console.log(res); })
      .catch( function(error){ console.log(error); })
  • axios.patch( url , [data], [config] )

注: 在使用别名方法时, urlmethoddata 这些属性都不必在配置中指定。

3. 并发

使用自定义配置新建一个 axios实例: axios. create ( [config] )

var instance = axios.create( {
    baseURL : "https://some-domain.com/api/" ,
    timeout : 1000,
    headers : {"X-Custom-Header" : "foobar"}

});

实例的方法 有上面的 6种请求。且 指定的配置 将与 实例的配置 合并。

处理并发请求的助手函数: 

  •  axios . all ( iterable )    iterable : 迭代
  •  axios . spread( callback )

Axios执行多个并发请求: 

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){
       // 两个请求现在都执行完成
   } ) );

4. 请求配置

在创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。

  • url :  请求的服务器URL
  • method :  创建请求时使用的方法。
  • baseURL :  baseURL将自动添加在 url前面, 除非url是一个绝对URL。
  • transformRequest : 允许在向服务器发送前, 修改请求数据。
  • transformResponse : 允许在传递给 then/catch 前, 修改响应数据。
  • headers : 即将被发送的自定义请求头 。
  • ​​​​​​​params :  即将被与请求一起发送的URL参数。
  • ​​​​​​​paramsSerializer :​​​​​​​  是一个负责params序列化的函数
  • ​​​​​​​data : 作为请求主体被发送的数据。
  • ​​​​​​​timeout : 如果请求花费的时间超过timeoue值, 请求将被中断。
  • adapter :
  • ​​​​​​​auth :  表示应该使用HTTP基础验证,并提供凭据。
  • resoponseType : 表示服务器响应的数据类型。
  • ​​​​​​​xsrfCookieName: 用作xsrf token 的值的cookie的名称。
  • xsrfHeaderName : 是承载xsrf token 的值的HTTP头的名称。
  • ​​​​​​​onUploadProgress : 允许为上传处理进度事件。
  • onDownloadProgress : 允许为下载处理进度事件。
  • maxContentLength : 定义允许的响应内容的最大尺寸。
  • validateStatus : 定义对于给定的HTTP响应状态码
  • ​​​​​​​maxRedirects : 定义在node.js中follow的最大重定向数目。
  • ​​​​​​​httpAgent / httpsAgent :
  • ​​​​​​​proxy : 定义代理服务器的主机名和端口号。
  • cancelToken :  指定用于取消请求的 cancel token。
{
   url : '/user',
   methods: 'get',                           // 默认值 get
   baseURL: 'https: //some-domain.com/api/',
   transformRequest : [ function(data){
          // 对 data 进行任意转换处理
          return data;
      } ],
   transformResponse : [ function(data){
           // 对 data 进行任意转换处理
          return data;
      } ],
   headers : { 'X-Requested-With' : "XMLHttpRequest' },
   params : { 
          ID : 12345
      },
   paramsSerializer: function(params) {
          return Qs.stringify(params, {arrayFormat: 'brackets'})
     },
   data: {
         firstName: 'Fred'
     },
   timeout: 1000,
   withCredentials : false,                            // 默认值
   adapter: function (config) { },
   auth: {
         username: 'janedoe',
         password: 's00pers3cret'
     },
   responseType: 'json',                                // 默认值
   xsrfCookieName: 'XSRF-TOKEN',                        // 默认值
   xsrfHeaderName: 'X-XSRF-TOKEN',                      // 默认值
   onUploadProgress: function (progressEvent) {
        // 对原生进度事件的处理
     },
   onDownloadProgress: function (progressEvent) {
        // 对原生进度事件的处理
     }, 
   maxContentLength: 2000,
   validateStatus: function (status) {
         return status >= 200 && status < 300;     // 默认值
     },
   maxRedirects: 5,                                 // 默认值
   httpAgent: new http.Agent({ keepAlive: true }),
   httpsAgent: new https.Agent({ keepAlive: true }),
   proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: : {
           username: 'mikeymike',
           password: 'rapunz3l'
        }
     },
   cancelToken: new CancelToken(function (cancel) { })

}

5. 响应结构

某个请求的响应 包含以下信息: 

{
  data: {},           // `data` 由服务器提供的响应
  status: 200,        // `status` 来自服务器响应的 HTTP 状态码
  statusText: 'OK',   // `statusText` 来自服务器响应的 HTTP 状态信息
  headers: {},        // `headers` 服务器响应的头
  config: {}          // `config` 是为请求提供的配置信息
}

使用 then 时,将接收下面这样的响应:

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

在使用 catch 时,或传递 rejection callback 作为 then 的第二个参数时,响应可以通过 error 对象可被使用。正如在错误处理这一节所讲。

6. 配置的默认值/defaults

可以通过`axios.defaults.`指定将被 用在各个请求的配置默认值。

6.1 配置全局的axios默认值

axios.defaults.baseURL = "https://api.example.cpm';
axios.defaults.headers.common['Authorization] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = "application/x-www-form-urlencoded";  // 设置POST请求头类型

6.2 配置自定义的axios默认值

  • 创建实例时设置配置的默认值。
    var instance = axios.create({
        baseURL : 'https://api.example.com'
    });
  • 在实例已经创建后修改默认值。
    instance.defaults.headers.common['Authorization'] =AUTH_TOKEN;

6.3 配置的优先顺序

配置会以一个优先顺序进行合并。

优先顺序是:  在` lib/defaults.js`找到的库的默认值 --> 然后是实例defaults属性 --> 最后是 请求的config参数。

后者将优于前者。

 // 使用有库提供的配置默认值来创建实例
var instance = axios.create();     // 此时超时配置的默认值为 0


 // 覆写 库的超时默认值
instance.defaults.timeout = 2500;   // 此时,在超时前,所有请求会等待2.5秒


 // 为已知需要花费很长时间的请求 覆写超时设置
instance.get( '/longRequest', {
    timeout : 5000
});

7. 拦截器

使用`axios.interceptors.` 在 请求或响应 被  then或catch处理前  拦截它们。

  • 添加 请求拦截器 : axios.interceptors.request.use()
  • 添加 响应拦截器 : axios.interceptors.response.use()
   // 添加 请求拦截器
axios.interceptors.request.use( function(config){
      // 在发送请求前做些什么
      return config;
} , function(error){
      // 对错误做些什么
      return Promise.reject(error);
} );



   // 添加 响应拦截器
axios.interceptors.response.use( function(res){
      // 对响应的数据做些什么
      return res;
} , function(error){
      // 对错误做些什么
      return Promise.reject(error);
} );

为自定义的Axios实例添加拦截器: 

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

移除拦截器: axios.interceptors.request.eject( 拦截器名称 );

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

8. 错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
         // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
         // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

 使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 状态码在大于或等于500时才会 reject
  }
})

9. 取消

使用 cancel token 取消请求

Axios 的 cancel token API 基于cancelable promises proposal,它还处于第一阶段。

使用 CancelToken.source 工厂方法创建 cancel token :

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

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理错误
  }
});

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});

// 取消请求
cancel();

注 : 可以使用同一个 cancel token 取消多个请求

 

猜你喜欢

转载自blog.csdn.net/wei_jia007/article/details/82352721