# axios发送ajax请求
# 基础写法
<body>
    <button>GET</button>
    <button>POST</button>
    <button>AJAX</button>
</body>
<script>
    let btns = document.querySelectorAll('button');
    // 配置baseURL,对路径进行一个简化,下面就不需要基础路径了
    axios.defaults.baseURL = 'http://127.0.0.1:8000'
    btns[0].onclick = function () {
        // GET请求
        axios.get('/axios-serve', {//设置URL参数
            params: {
                id: 100,
                vip: 7
            },
            headers: {//设置请求头信息,出问题就把H大写
                name: 'jack',
                age: 18
            }
        }).then(value => { console.log(value) })//promise方法打印响应值
    }
    btns[1].onclick = function () {
        //POST请求,参数为url,数据(体),{其他配置}。比GET多了一个体
        axios.post('/axios-serve', {//请求体
            username: 'admin',
            password: 'admin'
        }, {
            params: {//url参数
                id: 200,
                vip: 8
            },
            headers: {//设置请求头信息,报错就把H大写
                width: 200,
                height: 200,
            }
        });
    }
    //常用方法
    btns[2].onclick = function () {
        //axios通用方法发送请求
        axios({
            method: 'POST',//请求方法
            url: '/axios-serve',//url
            params: {//url参数
                vip: 10,
                lv: 100,
            },
            headers: {//头信息
                a: 100,
                b: 200,
            },
            date: {//请求体参数
                username: 'admin',
                password: 'admin'
            }
        }).then(response=>{//打印响应信息
            console.log(response);
            //甚至可以直接打印响应的状态码,状态字符串,头信息,响应体
            console.log(response.status);//200
            console.log(response.statusText);//ok
            console.log(response.headers);//头
            console.log(response.data);//数据
        },
        error=>{
            console.log('请求失败了',error.message)        
        })
    }
</script>
 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
63
64
65
66
67
68
69
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
63
64
65
66
67
68
69