Categories: Axios 教程

Axios 概要

什么是Axios?

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

特性

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

安装

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 CDN:

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

案例

  • 执行 GET 请求
// 为给定 ID 的 user 创建请求
axios.get(/user?ID=12345)
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });


// 上面的请求也可以这样做
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(), getUserPermission()])
    .then(axios.spread(function (acct, perms) {
        // 两个请求都执行完成
    }));

andy

前端小白,在Web176教程网这个平台跟大家一起学习,加油!

Share
Published by
andy

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

1 月 ago