-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
66 lines (61 loc) · 2.27 KB
/
index.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
63
64
65
66
const eeui = app.requireModule('eeui')
const stream = app.requireModule('stream')
// import MD5 from 'blueimp-md5' // 可以引入npm包,当你需要时
import apiList from './api/apis.js'
// root-api
const API_BaseUrl = 'http://10.0.0.140:8080'
Vue.mixin({
data() {
return {
}
},
created() {},
methods: {
// 全局请求函数
$fetch(options) {
// 缓存获取登录token
let user_token = eeui.getCachesString('user_token')
let apiUrl = `${API_BaseUrl}${apiList[options.name]}`
// 支持name和url
apiUrl = options.url || apiUrl
// 支持methods和method
options.method = options.method || options.methods
options.headers = options.headers || {}
options.data = options.data || {}
// 添加自定义全局参数,比如APP版本号
let versioncode = weex.config.env.appVersion
options.data.versioncode = versioncode
// 处理get请求
if (options.method.toLowerCase() === 'get' && options.data) {
apiUrl += '?';
for (let key in options.data) {
apiUrl += `&${key}=${options.data[key]}`
}
}
return new Promise((resolve, reject) => {
stream.fetch({
method: options.method,
url: apiUrl,
type: options.type || 'json',
headers: {
'Content-Type': 'application/json',
'Cookie': `token=${user_token}`, // 设置cookie
...options.headers
},
body: JSON.stringify(options.data)
}, (res) => {
if (res.ok && res.status === 200) {
let data = res.data || {}
// 可根据返回字段全局处理错误
// if (data.error === 1) {
// eeui.toast('加载出错了');
// }
resolve(data)
} else {
reject(res)
}
});
})
}
}
});