什么是 axios? Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性 
浏览器支持 
 
 
Latest ✔ 
Latest ✔ 
Latest ✔ 
Latest ✔ 
Latest ✔ 
8+ ✔ 
 
安装 使用 npm:
使用 bower:
使用 cdn:
1 <script src="https://unpkg.com/axios/dist/axios.min.js" ></script> 
案例 执行 GET 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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)   }) 
执行 POST 请求
1 2 3 4 5 6 7 8 9 10 11 axios   .post ('/user' , {     firstName : 'Fred' ,     lastName : 'Flintstone'    })   .then (function  (response ) {     console .log (response)   })   .catch (function  (error ) {     console .log (error)   }) 
执行多个并发请求
1 2 3 4 5 6 7 8 9 10 11 12 13 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 ) {        }) ) 
axios API 可以通过向 axios 传递相关配置来创建请求
axios(config) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 axios ({  method : 'post' ,   url : '/user/12345' ,   data : {     firstName : 'Fred' ,     lastName : 'Flintstone'    } }) axios ({  method : 'get' ,   url : 'http://bit.ly/2mTM3nY' ,   responseType : 'stream'  }).then (function  (response ) {   response.data .pipe (fs.createWriteStream ('ada_lovelace.jpg' )) }) 
axios(url[, config]) 请求方法的别名 为方便起见,为所有支持的请求方法提供了别名
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]]) 注意 在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
并发 处理并发请求的助手函数
axios.all(iterable) axios.spread(callback) 创建实例 可以使用自定义配置新建一个 axios 实例
axios.create([config]) 1 2 3 4 5 const  instance = axios.create ({  baseURL : 'https://some-domain.com/api/' ,   timeout : 1000 ,   headers : { 'X-Custom-Header' : 'foobar'  } }) 
实例方法 以下是可用的实例方法。指定的配置将与实例的配置合并。
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]]) 请求配置 这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 {       url : '/user' ,      method : 'get' ,          baseURL : 'https://some-domain.com/api/' ,            transformRequest : [function  (data, headers ) {          return  data;   }],      transformResponse : [function  (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' ,          responseEncoding : 'utf8' ,        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 ,                socketPath : null ,          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 ) {   }) } 
响应结构 某个请求的响应包含以下信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 {      data : {},      status : 200 ,      statusText : 'OK' ,      headers : {},       config : {},              request : {} } 
使用 then 时,你将接收下面这样的响应 :
1 2 3 4 5 6 7 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 ) }) 
在使用 catch 时,或传递 rejection callback  作为 then 的第二个参数时,响应可以通过 error 对象可被使用,正如在错误处理 这一节所讲。
配置默认值 你可以指定将被用在各个请求的配置默认值
全局的 axios 默认值 1 2 3 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'  
自定义实例默认值 1 2 3 4 5 6 7 const  instance = axios.create ({  baseURL : 'https://api.example.com'  }) instance.defaults .headers .common ['Authorization' ] = AUTH_TOKEN  
配置的优先顺序 配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。这里是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 var  instance = axios.create ()instance.defaults .timeout  = 2500  instance.get ('/longRequest' , {   timeout : 5000  }) 
拦截器 在请求或响应被 then 或 catch 处理前拦截它们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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)   } ) 
如果你想在稍后移除拦截器,可以这样:
1 2 3 4 const  myInterceptor = axios.interceptors .request .use (function  (   }) axios.interceptors .request .eject (myInterceptor) 
可以为自定义 axios 实例添加拦截器
1 2 3 4 const  instance = axios.create ()instance.interceptors .request .use (function  (    }) 
错误处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 axios.get ('/user/12345' ).catch (function  (error ) {   if  (error.response ) {               console .log (error.response .data )     console .log (error.response .status )     console .log (error.response .headers )   } else  if  (error.request ) {                    console .log (error.request )   } else  {          console .log ('Error' , error.message )   }   console .log (error.config ) }) 
Y 可以使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。
1 2 3 4 5 axios.get ('/user/12345' , {   validateStatus : function  (status ) {     return  status < 500     } }) 
取消 使用 cancel token  取消请求
Axios 的 cancel token API 基于cancelable promises proposal ,它还处于第一阶段。
 
可以使用 CancelToken.source 工厂方法创建 cancel token,像这样:
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 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  {            }   }) axios.post (   '/user/12345' ,   {     name : 'new name'    },   {     cancelToken : source.token    } ) source.cancel ('Operation canceled by the user.' ) 
还可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:
1 2 3 4 5 6 7 8 9 10 11 12 const  CancelToken  = axios.CancelToken let  cancelaxios.get ('/user/12345' , {   cancelToken : new  CancelToken (function  executor (c ) {          cancel = c   }) }) cancel ()
注意: 可以使用同一个 cancel token 取消多个请求
 
默认情况下,axios 将 JavaScript 对象序列化为 JSON。 要以 application / x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一。
浏览器 在浏览器中,您可以使用 URLSearchParams API,如下所示:
1 2 3 4 const  params = new  URLSearchParams ()params.append ('param1' , 'value1' ) params.append ('param2' , 'value2' ) axios.post ('/foo' , params) 
请注意,所有浏览器都不支持 URLSearchParams(请参阅 caniuse.com),但可以使用 polyfill(确保填充全局环境)。
 
或者,您可以使用 qs 库编码数据:
1 2 const  qs = require ('qs' )axios.post ('/foo' , qs.stringify ({ bar : 123  })) 
或者以另一种方式(ES6),
1 2 3 4 5 6 7 8 9 import  qs from  'qs' const  data = { bar : 123  }const  options = {  method : 'POST' ,   headers : { 'content-type' : 'application/x-www-form-urlencoded'  },   data : qs.stringify (data),   url } axios (options)
Node.js 在 node.js 中,您可以使用 querystring 模块,如下所示:
1 2 const  querystring = require ('querystring' )axios.post ('http://something.com/' , querystring.stringify ({ foo : 'bar'  })) 
您也可以使用 qs 库。
Semver 在 axios 达到 1.0 版本之前,破坏性更改将以新的次要版本发布。 例如 0.5.1 和 0.5.4 将具有相同的 API,但 0.6.0 将具有重大变化。
Promises axios 依赖原生的 ES6 Promise 实现而被支持 . 如果你的环境不支持 ES6 Promise,你可以使用 polyfill .
TypeScript axios 包括 TypeScript 定义。
1 2 import  axios from  'axios' axios.get ('/user?ID=12345' )