请求

请求

1、封装请求

requset.js用于封装请求
然后api文件夹添加请求方法

  • uniapp封装uni.requset
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
import store from '@/store/store.js'
export default {
common: {
url: "http://localhost:3000/api",
// url: baseUrl + "/api",
data: {},
header: {
"Content-Type": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
method: "GET",
dataType: "json"
},
// options-请求参数
request(options = {}) {
uni.showLoading({
title: '加载中'
});

options.url = this.common.url + options.url;
options.data = options.data || this.common.data;
options.header = options.header || this.common.header;
options.method = options.method || this.common.method;
options.dataType = options.dataType || this.common.dataType;

// 判断是否传入了header头的token进行用户是否登录的验证
if (options.header.token) {
const token = store.state.user.token;
if (!token) {
uni.showToast({
title: "请先登录",
icon: "none"
})
return uni.navigateTo({
url: "/pages/login/login"
})
} else {
options.header.Authorization = `Bearer ${token}`
}
}
let requestTask;
// 返回一个promise
const promie = new Promise((res, rej) => {
requestTask =
uni.request({
...options,
success: (result) => {
// console.log("成功*******************");
// console.log("result的结果");
// console.log(result);
if (result.statusCode != 200) {
uni.hideLoading();
return rej();
}
// 关闭加载中
uni.hideLoading();
let data = result.data
res(data);
},
fail: (err) => {
uni.hideLoading();
uni.showToast({
title: '请求失败,请检查网络',
icon: 'none',
duration: 2000
})
rej(err)
}
})
})
// 给promise添加一个abort方法,用于取消请求
promie.abort = () => {
requestTask && requestTask.abort();
}
return promie;
}
}

方法,api文件夹的order.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import $http from '@/config/request.js'
export function payCart(order_id,payStatus) {
return $http.request({
url: "/orders/pay",
method: 'put',
header: {
token: true
},
data: {
order_id: order_id,
payStatus:payStatus
}
})
}

使用

1
2
3
4
5
6
7
8
9
payCart(this.order_id, this.payStatus).then((res) => {
console.log(res)
}).catch(err => {
console.log(err);
})
// 设置一个定时器,如果 5 秒钟之后还没有获取到数据,就终止请求
setTimeout(() => {
payCart().abort()
},5000)

2、设置请求重载

可以通过封装一个请求重试的函数,在请求失败时判断当前重试次数是否小于限定的最大重试次数,若小于则延迟一定时间后再次发起请求,并增加重试次数,若大于则停止重试。

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
// 封装一个请求重试函数
function retryRequest(options, maxRetry = 3, interval = 1000) {
let retryCount = 0; // 重试次数
const request = () => {
uni.request({
...options,
success(res) {
options.success && options.success(res);
},
fail(err) {
if (retryCount < maxRetry) { // 如果重试次数小于最大重试次数
retryCount++; // 增加重试次数
setTimeout(() => { // 延迟一定时间后再次发起请求
request();
}, interval);
} else { // 如果重试次数大于等于最大重试次数
options.fail && options.fail(err); // 请求失败
}
}
});
};
request();
}

// 使用示例
retryRequest({
url: 'http://example.com/api',
method: 'GET',
success(res) {
console.log(res);
},
fail(err) {
console.log(err);
}
}, 3, 1000); // 最大重试次数为 3,重试间隔为 1000ms

xhr

1
2
3
4
5
6
7
8
9
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true); // 设置请求方法、URL和异步标志
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) { // 检查请求的状态和响应的状态码
const response = JSON.parse(xhr.responseText); // 解析响应数据
console.log(response);
}
};
xhr.send(); // 发送请求

fetch

1
2
3
4
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

Fetch API的response对象表示HTTP响应,它包含了与响应相关的信息和方法。response对象提供了多个属性和方法,用于访问和处理响应数据。

其中,常用的属性和方法有:

  • response.ok:一个只读的布尔值属性,表示响应是否成功(状态码在 200-299 范围内)。
  • response.status:一个只读的整数属性,表示响应的HTTP状态码。
  • response.statusText:一个只读的字符串属性,表示响应的HTTP状态文本。
  • response.headers:一个只读的 Headers 对象,表示响应头部信息。
  • response.json():一个方法,返回一个Promise,用于将响应体解析为JSON格式的JavaScript对象。
  • response.text():一个方法,返回一个Promise,用于将响应体解析为纯文本字符串。
  • response.blob():一个方法,返回一个Promise,用于将响应体解析为 Blob 对象。
  • response.arrayBuffer():一个方法,返回一个Promise,用于将响应体解析为 ArrayBuffer 数据。
  • response.formData():一个方法,返回一个Promise,用于将响应体解析为 FormData 对象。

根据需求,可以使用这些属性和方法来获取和处理响应数据。例如,可以使用response.json()方法将响应体解析为JSON对象,或者使用response.text()方法将响应体解析为文本字符串。

axios

1
2
3
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.log(error));

请求参数

FormData

表单数据格式,需要设置请求头的Content-Typeapplication/x-www-form-urlencoded

URLSearchParams


请求
https://xiehongchen.github.io/2023/04/22/请求/
作者
XieHongchen
发布于
2023年4月22日
许可协议