fetch.js
1.26 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
import {
Alert,
} from 'react-native';
const MAIN_URL = 'https://devpay.brae.co';
/**
*
* @param {String} url 形如'/some/directory/'的接口,以'/'开头
* @param {Object} data 上送数据
* @param {function} sucCB 成功回调函数
* @param {function} errCB 失败回调函数
* @param {Object} header 补充包头
*/
export default function post(url, data, sucCB, errCB, header = {}) {
const requestUrl = `${MAIN_URL}${url}`;
const body = JSON.stringify(data);
const headers = {
"Accept": "application/json",
"Content-Type": "application/json",
...header,
}
fetch(requestUrl, {
method: 'POST',
body: body,
headers: headers,
}).then(res => {
if (res && res.status === 200) {
return res.json();
} else {
throw new Error('server')
}
}).then(res => {
if (res && res.code === 200 && res.enmsg === 'ok') {
sucCB(res);
} else {
errCB(res);
}
}).catch(err => {
console.log(err)
// 所有非 200 的情况都作为服务器内部错误处理
if (err.message === 'server') {
errCB({ code: 500, enmsg: 'server error', cnmsg: '服务器内部错误', data: null });
} else {
errCB({ code: 500, enmsg: 'client error', cnmsg: '网络异常', data: null });
}
})
}