Last active
November 21, 2018 10:32
-
-
Save vontell068/4f21e8b9fea4aae3375971318eb0729f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from 'dva/fetch'; | |
import config from '../config'; | |
import { Toast } from 'antd-mobile'; | |
import { getAccessToken } from './authority'; | |
const codeMessage = { | |
200: '数据获取成功', | |
201: '操作成功', | |
202: '已加入任务队列', | |
204: '删除成功', | |
400: '操作失败', | |
401: '授权失败', | |
403: '拒绝访问', | |
404: '页面不存在', | |
422: '数据验证失败', | |
500: '服务发生异常', | |
502: '服务当前不可用, 请稍后再试', | |
503: '服务器开小差了, 请稍后再试', | |
504: '服务访问超时, 请稍后再试', | |
}; | |
const checkStatus = response => { | |
if (response.status >= 200 && response.status < 300) { | |
return response; | |
} | |
const errortext = codeMessage[response.status] || response.statusText; | |
const error = new Error(errortext); | |
error.name = response.status; | |
error.response = response; | |
error.errortext = errortext; | |
throw error; | |
}; | |
/** | |
* Requests a URL, returning a promise. | |
* | |
* @param {string} url The URL we want to request | |
* @param {object} [option] The options we want to pass to "fetch" | |
* @return {object} An object containing either "data" or "err" | |
*/ | |
export function request(url, option) { | |
const options = { | |
...option, | |
}; | |
/** | |
* Produce fingerprints based on url and parameters | |
* Maybe url has the same parameters | |
*/ | |
const defaultOptions = { | |
credentials: 'include', | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json; charset=utf-8', | |
Authorization: `${config.authPrefix} ${getAccessToken()}`, | |
} | |
}; | |
const newOptions = { ...defaultOptions, ...options }; | |
if ( | |
newOptions.method === 'POST' || | |
newOptions.method === 'PUT' || | |
newOptions.method === 'DELETE' | |
) { | |
newOptions.body = JSON.stringify(newOptions.body); | |
} | |
return fetch(config.baseUrl + url, newOptions) | |
.then(checkStatus) | |
.then(response => { | |
if (newOptions.method === 'DELETE' || response.status === 204) { | |
return response.text(); | |
} | |
return response.json().then(data => data); | |
}).catch(e => { | |
const status = e.name; | |
Toast.fail(`请求错误 ${status}: ${e.errortext}`, 2, () => { | |
if (status === 401) { | |
// @HACK | |
/* eslint-disable no-underscore-dangle */ | |
window.location.href = '/go_mobile'; | |
return; | |
} | |
// environment should not be used | |
if (status === 403) { | |
return; | |
} | |
if (status <= 504 && status >= 500) { | |
return | |
}; | |
if (status >= 404 && status < 422) { | |
return; | |
} | |
}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment