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

axios安装

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

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

入门使用

function getMessage(){
  axios.get('http://localhost:8110/admin/edu/teacher/list').then(response => {
    console.log(response);
  }).catch(error => {
    console.log(error);
  })
}

业务分层

// 初始化axios设置,返回一个函数引用
function instance(){
  return axios.create({
    baseURL: 'http://localhost:8110',
    timeout: 5000 // 请求超时时间
  })
}

// api访问模块
function api(){
  let i = instance();
  return i({
    url: '/admin/edu/teacher/list',
    method: 'get'
  })
}

// 调用
function getMessage2(){
  api().then(response => {
    console.log(response);
  })
}

完整示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<button onclick="getMessage()">axios请求一</button>
<button onclick="getMessage2()">axios请求二</button>
<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        function getMessage(){
            console.log("一");
            axios.get('http://localhost:8110/admin/edu/teacher/list').then(response => {
                console.log(response);
            }).catch(error => {
                console.log(error);
            })
        }

        // 初始化axios设置,返回一个函数引用
        function instance(){
            return axios.create({
                baseURL: 'http://localhost:8110',
                timeout: 5000 // 请求超时时间
            })
        }

        // api访问模块
        function api(){
            let i = instance();
            return i({
                url: '/admin/edu/teacher/list',
                method: 'get'
            })
        }

        // 调用
        function getMessage2(){
            console.log("二");
            api().then(response => {
                console.log(response);
            })
        }
    </script>
</body>
</html>

Last modification:November 12, 2020
如果觉得我的文章对你有用,请随意赞赏