create-api.js
1.43 KB
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
import axios from 'axios';
import iView from 'iview';
import bus from 'utils/bus';
const baseParams = {
app_version: '6.6.0',
business_line: 'yohobuy',
client_type: 'miniapp',
debug: 'XYZ',
_sncp: 'NGJjYjhkNmwwZGM0OTk0YmQyMTMwZjlmoTZmzjY4cjN'
};
class CreateApi {
constructor({baseURL}) {
this.$api = axios.create({
baseURL
});
this.$api.defaults.headers = {
'X-Requested-With': 'XMLHttpRequest'
};
}
async get(url, params, options) {
return await this._request(Object.assign({
url,
params: Object.assign({}, params, baseParams),
method: 'get'
}), options);
}
async post(url, data, options) {
return await this._request(Object.assign({
url,
data: Object.assign({}, data, baseParams),
method: 'post'
}, options));
}
_errHandle({response}) {
let error = {
code: 500,
message: response.data && response.data.message || '接口异常'
};
if (response.status === 401) {
const {data} = response;
if (data) {
error = data;
if (data.code !== 999) {
bus.$emit('logout');
}
}
}
return Promise.reject(error);
}
async _request(options) {
try {
return await this.$api(options).then(res => res.data, this._errHandle);
} catch ({message}) {
iView.Message.destroy();
iView.Message.warning(message);
return void 0;
}
}
}
export default CreateApi;