4、axios 入门和安装

251 阅读2分钟

一.技术说明

1.axios.js 是一个基于 promise 的 HTTP 库,支持浏览器和 Node 环境;

2.说明白点,就是使用这个库来执行 Ajax 请求,获取 JSON 数据;

3.我们可以利用 axios 可以发送 get、post 等一系列请求,然后得到数据;

二.安装测试

1.安装方式,我们这里提供两种,一种在 node 下运行,另一种在浏览器下运行;

2.第一种方式,在命令行运行如下命令,加载需要的包:

npm install axios

3.如果要在浏览器使用 axios,直接可以使用 cdn 地址加载即可;

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

4.如果有条件有本地服务器,可以本地测试,没有的,提供了一个网络地址:(数据在下面)

cdn.liyanhui.com/data.json(可…

5.我们先用简单的方式在 Node 环境下实现远程获取 json 数据;

const axios = require('axios');

//使用 get 请求获取数据
axios.get('https://cdn.liyanhui.com/data.json')
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log('错误:' + err);
});

6.浏览器执行远程 Ajax 请求会有跨域问题,我们可以保存到本地执行即可;

7.因为本地 IDE 具有内置服务器功能,可以直接套用运行;

https://cdn.liyanhui.com/data.json (可跨域,设置过)

https://cdn.ycku.com/data.json (不可跨域,默认)

练习代码:

html文件练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        axios.get('http://localhost:63342/Mock/04/data.json?_ijt=cat6bibqdiut2fkge51rtfs9sg')
            .then(res => {
                console.log(res.data);
            })
            .catch(err => {
                console.log('错误' + err);
            });
    </script>
</head>
<body>

</body>
</html>

image.png

js文件练习

const axios = require('axios');

axios.get('http://localhost:63342/Mock/04/data.json?_ijt=b1jcepg1p1q609g7h4jnrvdlg2')
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log('错误' + err);
    });

JSON数据

[
  {
    "id": 19,
    "username": "蜡笔小新",
    "gender": "男",
    "email": "xiaoxin@163.com",
    "price": "60.00"
  },
  {
    "id": 20,
    "username": "路飞",
    "gender": "男",
    "email": "lufei@163.com",
    "price": "70.00"
  },
  {
    "id": 21,
    "username": "黑崎一护",
    "gender": "男",
    "email": "yihu@163.com",
    "price": "80.00"
  },
  {
    "id": 24,
    "username": "小明",
    "gender": "男",
    "email": "xiaoming@163.com",
    "price": "90.00"
  },
  {
    "id": 25,
    "username": "孙悟饭",
    "gender": "男",
    "email": "wufan@163.com",
    "price": "100.00"
  },
  {
    "id": 26,
    "username": "孙悟天",
    "gender": "男",
    "email": "wutian@163.com",
    "price": "110.00"
  },
  {
    "id": 27,
    "username": "樱桃小丸子",
    "gender": "女",
    "email": "yingtao@163.com",
    "price": "77.00"
  },
  {
    "id": 29,
    "username": "孙悟空",
    "gender": "男",
    "email": "wukong@163.com",
    "price": "100.00"
  },
  {
    "id": 76,
    "username": "李白",
    "gender": "男",
    "email": "UPPER(EMAIL)",
    "price": "52.00"
  },
  {
    "id": 79,
    "username": "辉夜",
    "gender": "女",
    "email": "HUIYE@163.COM",
    "price": "91.00"
  },
  {
    "id": 80,
    "username": "李黑",
    "gender": "男",
    "email": "lihei@163.com",
    "price": "99.00"
  }
]