风华正茂、时光流逝、真爱时光、努力创建辉煌。

axios 中文文档

 

 

 

axios 是基于Promise 的http客户端,可以用于浏览器和node.js。

特点

  • 浏览器使用 XMLHttpRequests
  • node.js使用http请求
  • 支持Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 浏览器端支持防止CSRF(跨站请求伪造

支持的浏览器


 

 


 

 

安装

使用npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 yarn

$ yarn add axios

使用 cdn:

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

 

举例

发起GET请求,(get请求三种写法)

const axios = require('axios');

// Make a request for a user with a given ID  请求具有给定ID的用户
axios.get('/user?ID=12345')      //这个请求参数直接在路径上面
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// 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);
  })
  .finally(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.  要使用async/await吗?将“async”关键字添加到外部函数/方法。
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

 

NOTE: async/await is part of ECMAScript 2017 and is not supported in Internet
Explorer and older browsers, so use with caution.

注意:async/await是ECMAScript 2017的一部分,在Internet上不受支持

资源管理器和较旧的浏览器,请谨慎使用。

 

 

 

 发起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
  }));

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
 
 
 
 
 
 
 
posted @ 2019-12-26 16:53  野马,程序源改造新Bug  阅读(188)  评论(0编辑  收藏  举报