介绍

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"></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(), getUserPermissions()])
    8. .then(axios.spread(function (acct, perms) {
    9. // 两个请求都成功执行
    10. }));

    axios API

    可以通过向 axios 传递相关配置来创建请求

    axios(config)

  • GET

    1. // 获取远端图片
    2. axios({
    3. method:'get',
    4. url:'http://bit.ly/2mTM3nY',
    5. responseType:'stream'
    6. })
    7. .then(function(response) {
    8. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    9. });
  • POST

    1. axios({
    2. method: 'post',
    3. url: '/user/12345',
    4. data: {
    5. firstName: 'Fred',
    6. lastName: 'Flintstone'
    7. }
    8. });

axios(url[,config])

  1. // 发送 GET 请求(默认的方法)
  2. axios('/user/12345');