Axios基于 Promise 的 HTTP 客户端

联合创作 · 2023-09-23 15:19

Axios,基于 Promise 的 HTTP 客户端,可以工作于浏览器中,也可以在 node.js 中使用。


功能:



  • 从浏览器中创建 XMLHttpRequest


  • 从 node.js 中创建 http 请求


  • 支持 Promise API


  • 拦截请求和响应


  • 转换请求和响应数据


  • 取消请求


  • 自动转换 JSON 数据


  • 客户端支持防止 XSRF 攻击



示例代码:


执行一个 GET 请求



// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行一个 POST 请求



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

执行多个并发请求



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
  }));
浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报