美文网首页
初识Axios

初识Axios

作者: 花泽冒菜 | 来源:发表于2019-04-28 20:02 被阅读0次

axios是一个基于promise的浏览器端和Node端的HTTP客户端(Promise Based HTTP Client for the Browser And Node.js)。

主要有以下作用:

  • 从浏览器端发起XMLHttpRequests
  • 从node端发起http请求
  • 支持Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换成JSON数据
  • 为客户端提供防止SXRF攻击保护

使用方法

GET请求示例:

const axios = require('axios');
// 请求一个给定id的用户
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // 不管请求成功与否都会执行
  });

// 还可以使用以下写法
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // 不管请求成功与否都会执行
  });  

// 还可以配合async/await使用,但要注意浏览器兼容性
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

POST请求示例:

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

多个并发请求(concurrent requests)示例:

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) {
    // Both requests are now complete
  }));

使用方式跟fetch大同小异,详情请见axios的readme文档。

Reference

1.https://github.com/axios/axios

相关文章

网友评论

      本文标题:初识Axios

      本文链接:https://www.haomeiwen.com/subject/zjajnqtx.html