# 请求后端API

jQuery,fetch,axios异步请求后端API

# 一、jQuery

// 基本用法无参数get请求
$.ajax({
    url:"demo_test.txt",
    success:function(result){
        console.log(result);
    }
}
// 需指定方法则增加method字段
$.ajax({
    url:"demo_test.txt",
    method:"POST",
    success:function(result){
	console.log(result);
    }
}
// 有参数,则增加data字段,有请求头则增加headers字段,有错误处理增加error字段
// 默认是按照表单提交post方法,data中虽然是json但是提交时转成表单
$.ajax({
    url:"demo_test.txt",
    data:{a:10},
    success:function(result){
    	console.log(result);
    },
    error:function(xhr,status,error){
    	console.log(error);
    }
});
// data在post下是表单格式,在get下是querystring格式
// 通过以下方法指定为json格式[json格式本质就是body里是json字符串,头里是application/json]
$.ajax({
    url:"demo_test.txt",
    headers:{ contentType: "application/json"},
    method:"POST",
    data:JSON.stringify({a:10}),
    success:function(result){
	console.log(result);
    }
});
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
# 其他案例1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试Ajax发送Http请求</title>
</head>
<body>
    <!-- 点击 触发提交 -->
    <button id='btn'>post</button>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
    <script>
        $("#btn").click(function(){
            var jsonData = {
                appName: "WeChat_Card_Ext",
                userId: "U100069823",
                userToken: "-VQwR4VstNo-xuINdcw/UiUuxrbNBrUAV36WgvRztbTlc-mYW7h1eMXaikZ/mPDRME5laitBDfPGz9IgvSRslRhuQflzZFAHvPO4K0UxVHshpzrqXXBdqAu-FAItaxDAfVYQpxgwohYXVvKV9s0kDeI2aFjOh8X1TgUGTwh169Ok1rNi6TsQlUPUteAUi/1/"
            }
            $.ajax({
                headers:{'Content-Type':'application/json;charset=utf8','cityen':'gz', 'platform':'wechat'},
                url: "http://mobileapi-test.centaline.com.cn/json/reply/BindStaffAndPushAplusMsg",
                type: "post",
                data: JSON.stringify(jsonData),
                dataType: "json",
                success: function(data){
                    alert(data)
                },
                error: function(msg){
                    alert("ajax连接异常:"+msg);
                }
            });
        });
    </script>
</body>
</html>
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
# 其他案例2-请求列表渲染表格
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <style>
        /* Border styles */
        #table-2 {
            padding: 0;
            margin: 0;
            border-collapse: collapse;
        }
        #table-2 thead,
        #table-2 tr {
            border-top-width: 1px;
            border-top-style: solid;
            border-top-color: rgb(230, 189, 189);
        }
        #table-2 {
            border-bottom-width: 1px;
            border-bottom-style: solid;
            border-bottom-color: rgb(230, 189, 189);
        }
        /* Padding and font style */
        #table-2 td,
        #table-2 th {
            padding: 5px 10px;
            font-size: 12px;
            font-family: Verdana;
            color: rgb(177, 106, 104);
        }
        /* Alternating background colors */
        #table-2 tr:nth-child(even) {
            background: rgb(238, 211, 210)
        }
        #table-2 tr:nth-child(odd) {
            background: #FFF
        }

    </style>
</head>
<body>
    <button id='btn'>测试</button>
    <table id="table-2"></table>
    <script>
        window.onload = function () {
            showdata();
        }
        $('#btn').click(function () {
            showdata();
        });
        function showdata() {
            var url = ''
            if ($('#btn').html() == '线上') {
                $('#btn').html('测试')
                url = "http://mobileapi-test.centaline.com.cn/json/reply/CityUrlAddressList"
            } else {
                url = 'https://mobileapi.centanet.com/v6/java/json/reply/CityUrlAddressList'
                $('#btn').html("线上")
            }
            $.ajax({
                headers: { 'version': 'v6.2' },
                url: url,
                type: "GET",
                crossDomain: true,
                success: function (data) {
                    listCity(data.Result)
                },
                error: function (e) {
                    console.log(e, 'ajax连接异常:error');
                }
            });
        }
        function listCity(data) {
            var table = $('#table-2');
            table.empty();
            //拼接表头
            table.append("<thead><tr><th>Code</th><th>名称</th><th>En名称</th><th>cityen</th><th>Abbr</th><th>passport</th></tr></thead>");
            for (var i = 0; i < data.length; i++) {
                //拼接表格的行和列
                var str = "<tr><td>" + data[i].Code + "</td><td>" + data[i].CityName + "</td><td>" + data[i].Spell + "</td><td>" + data[i].CityEn + "</td><td>" + data[i].Abbr + "</td><td>" + data[i].UserCenterUrl + "</td></tr>";
                //追加到table中
                table.append(str);
            }
        }
    </script>
</body>
</html>
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

JS和JSON互转

var obj = {a:"hello",b="world"}; //这是一个js对象,注意键名也是可以使用引号包裹的
var json = '{"a":"hello","b":"world"}'; //这是一个JSON字符串,本质是一个字符串

//互转
#1.JSON字符串转JS对象
var obj = JSON.parse('{"a":"hello","b":"world"}'); //结果是 {a:"hello",b="world"}
#2.JS对象转JSON字符串
var json = JSON.stringify({a:"hello",b="world"}); // 结果是 '{"a":"hello","b":"world"}'
1
2
3
4
5
6
7
8

# 二、fetch

// fetch的post表单数据用法
fetch(url,{
    headers:{
         'content-type': "application/x-www-form-urlencoded"
    },
    method:"POST",
    body:"a=12&b=33",
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
// fetch的post json数据用法
fetch(url,{
    headers:{
         'content-type': "application/json"
    },
    method:"POST",
    body:JSON.stringify({a:100}),
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

简写

#jQuery的get和post可以简写:
$.get(url,data,callback)  // querystring格式
$.post(url,data,callback) // x-www-form-urlencoded格式
#axios的get/post/put/delete等等都可以简写
axios.post(url,data).then(callback)
1
2
3
4
5

# 三、Axios

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

// axios默认是json类型的提交
axios({
    url:"http://localhost:99?x=1",
    method:"POST",
    data:{a:12}
})
.then(res=>console.log(res.data))
// 如果想改成form则需要修改headers和data格式
axios({
    url:"http://localhost:99?x=1",
    method:"POST",
    headers:{"Content-Type":"application/x-www-form-urlencoded"},
    data:"a=12&b=23"
})
.then(res=>console.log(res.data))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Vue里封装Axios为工具类

  1. 安装 npm install axios

  2. request.js 工具类

    import axios from "axios"
    
    // 创建axios实例
    const request = axios.create({
        baseURL: 'http://127.0.0.1:9999', //请求的URL公共部分
        timeout: 30000  //超时时间 30s
    })
    
    
    //请求拦截器
    request.interceptors.request.use(
        config => {
            // 是否需要设置 token
            const isToken = (config.headers || {}).isToken === false
            if (getToken() && !isToken) {
              config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
            }
            config.headers['Content-Type'] = 'application/json;charset=utf-8'
            return config
        }, error => {
            console.log(error)
            return Promise.reject(error)
        }
    )
    
    
    //响应拦截器
    request.interceptors.response.use(
        response => {
            const res = response.data
            // do something
            return res
        }, error => {
            console.log('err' + error)
            let { message } = error
            if (message == 'Network Error') {
              message = '后端接口连接异常'
            } else if (message.includes('timeout')) {
              message = '系统接口请求超时'
            } else if (message.includes('Request failed with status code')) {
              message = '系统接口' + message.substr(message.length - 3) + '异常'
            }
            //TODO 提示或打印message 使用element-ui的Message很好
            console.log(message)
            return Promise.reject(error)
        }
    )
    
    
    export default request
    
    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