将uni-request进行axios化封装

本文介绍如何将uni-app提供的网络请求方式uni-request进行封装。

step1

首先我们使用hubuilderX创建一个uni-app项目,并在根目录下创建目录common,用于统一存放我们的的工具类。

step2

common下新建axios/axios.js,并贴上如下代码:

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

const url_config ="你的接口地址"

function axios(options){
const {url, method, data}=options
const api_token =uni.getStorageSync('api_token');
let headers={
Authorization:'Bearer ' + api_token,
TargetLanguage:"zh-CN"
}

return uni.request({
url: url_config + url,
method,
data,
dataType: 'json',
header: headers
}).then(res => {
const result=res[1]
return checkStatus(result)
}).catch(parmas => {
console.log(parmas,'parmas')
})
}
function checkStatus(response){
return new Promise((resolve, reject)=>{
if(response.statusCode===200||
response.statusCode === 304 ||
response.statusCode === 400){
resolve(response.data);
}else{
reject({
status: response.statusCode,
message: response.data.message,
error: response.data.errors[Object.keys(response.data.errors)[0]][0]
});
}
})
}

export default {
post(url, params) {
return axios({url, method:"post", data:params}).then(response => {
return response
});
},
get(url, params) {
return axios({url, method:"get", data:params}).then(response => {
return response
});
},
delete(url, params) {
return axios({url, method:"delete", data:params}).then(response => {
return response
});
},
put(url, params) {
return axios({url, method:"put", data:params}).then(response => {
return response
});
},
}

step3

将我们封装好的axios挂载到全局,编辑main.js,

1
2
import axios from 'common/axios/axios.js'
Vue.prototype.$axios = axios;

到这边是不是已经开始熟悉起来了

step4

接下来我们就可以在需要发送网络请求的地方快乐的使用axios了

1
2
3
4
this.$axios.get(url,params).then(res=>{}).catch(e=>{console.log(e)})
this.$axios.post(url,params).then(res=>{}).catch(e=>{console.log(e)})
this.$axios.delete(url,params).then(res=>{}).catch(e=>{console.log(e)})
this.$axios.put(url,params).then(res=>{}).catch(e=>{console.log(e)})

在flutter中优雅的封装网络请求
在vue中对axios进行二次封装

文章作者: Joker
文章链接: https://qytayh.github.io/2020/11/%E5%B0%86uni-request%E8%BF%9B%E8%A1%8Caxios%E5%8C%96%E5%B0%81%E8%A3%85/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Joker's Blog