Axios


原生ajax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function getdoc() {
    var doc = new XMLHttpRequest();
    doc.open('GET', 'http://path');
    //形如:http://yapi.smart-xwork.cn/mock/169327/emp/list
    doc.send();
    doc.onreadystatechange = function () {
        if (doc.readyState == 4 && doc.status == 200) {
            document.getElementById('div').innerHTML = doc.responseText;
        }
    }
}

测试环境部署:

前置npm设置

1
npm config ls

prefix="…",将改路径加入到path环境变量中即可

json-server配置:

1
npm install -g json-server

建立db.json文件,并在内输入

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

然后在相应目录运行并启动服务器

1
json-server --watch db.json

启动后会给出三个url,分别用来访问对应的三个json对象


依赖引入

npm:

1
npm install axios

cdn:

1
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>

axios四个基本请求处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!--示例代码-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
</head>
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<script>
    const btns = document.querySelectorAll('button')
    btns[0].onclick=function (){
        axios({
			// 获取
            method:'GET',
            url:'http://localhost:3000/posts'
        }).then(response=>{
            console.log(response);
        })
    }
    btns[1].onclick=function (){
        axios({
			// 添加
            method:'POST',
            url:'http://localhost:3000/posts',
            data:{
                title:"ceshi",
                author:"haha"
            }
        }).then(response=>{
            console.log(response);
        })
    }
    btns[2].onclick=function (){
        axios({
			//按照url更改
            method:'PUT',
            url:'http://localhost:3000/posts/2',
            data:{
                title:"gaidong",
                author:"haha"
            }
        }).then(response=>{
            console.log(response);
        })
    }
    btns[3].onclick=function (){
        axios({
			//按照url删除
            method:'DELETE',
            url:'http://localhost:3000/posts/2'
        }).then(response=>{
            console.log(response);
        })
    }
</script>
</body>
</html>

axios请求响应处理

默认配置

1
2
3
4
axios.defaults.method='GET';//设置默认请求类型
axios.defaults.baseUrl='http://localhost:3000';//设置默认请求路径
axios.defaults.params={id:100};//设置默认参数
axios.defaults.timeout=3000;//设置结束请求最大时间

创建实例对象发送请求

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const c = axios.create({
    baseUrl: 'http://localhost:3000',
    timeout:3000
})
c({
    url:'/test',
}).then(respen=>{
    console.log(respen);
});
c.get('/test').then(respon=>{
    console.log(respon.data);
});

axios拦截器

请求先走请求拦截器,然后走相应拦截器,最后是自定义回调

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
基于Promise
// 添加拦截器
axios.interceptors.request.use(function (config) {
    console.log('请求拦截器成功')
    //请求成功
    return config;
}, function (error) {
    //请求失败
    console.log('请求拦截器失败')
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    console.log('响应拦截器成功')
    //响应成功
    return response;
}, function (error) {
    console.log('响应拦截器失败')
    // 响应拦截器失败
    return Promise.reject(error);
});

// 异步执行
axios({
    method: "GET",
    url: "http://localhost:3000/"
}).then(response => {
    console.log('自定义回调')
});

异常处理:若在请求成功处抛出异常,则响应拦截返回失败,异步捕获异常

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
基于Promise
// 添加拦截器
axios.interceptors.request.use(function (config) {
    console.log('请求拦截器成功')
    //请求成功
    throw '主动抛出异常'
}, function (error) {
    //请求失败
    console.log('请求拦截器失败')
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    console.log('响应拦截器成功')
    //响应成功
    return response;
}, function (error) {
    // 响应拦截器失败
    return Promise.reject(error);
});

// 异步执行
axios({
    method: "GET",
    url: "http://localhost:3000/"
}).then(response => {
    console.log('自定义回调')
}).cache(reson=>{
    console.log('自定义失败回调')
})