Axios起步

2022-02-28 11:40 更新

什么是Axios?

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


特性

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

安装

使用 npm:

  1. $ npm install axios

使用 bower:

  1. $ bower install axios

使用 CDN:

  1. <script src="https://unpkg.com/axios/dist/axios.min.js" rel="external nofollow" ></script>

案例

  • 执行 GET 请求
  1. // 为给定 ID 的 user 创建请求
  2. axios.get('/user?ID=12345')
  3.     .then(function (response) {
  4.         console.log(response);
  5.     })
  6.     .catch(function (error) {
  7.         console.log(error);
  8.     });
  9. // 上面的请求也可以这样做
  10. axios.get('/user', {
  11.         params: {
  12.             ID: 12345
  13.         }
  14.     })
  15.     .then(function (response) {
  16.         console.log(response);
  17.     })
  18.     .catch(function (error) {
  19.         console.log(error);
  20.     });
  • 执行 POST 请求
  1. axios.post('/user', {
  2.         firstname: 'Fred',
  3.         lastName: 'Flintstone'
  4.     })
  5.     .then(function (response) {
  6.         console.log(response);
  7.     })
  8.     .catch(function (error) {
  9.         console.log(error);
  10.     });
  • 执行多个并发请求
  1. function getUserAccount () {
  2.     return axios.get('/user/12345');
  3. }
  4. function getUserPermissions () {
  5.     return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermission()])
  8.     .then(axios.spread(function (acct, perms) {
  9.         // 两个请求都执行完成
  10.     }));


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号