request.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * 检查HTTP请求状态
  3. */
  4. function checkStatus(response) {
  5. if (response.status >= 200 && response.status < 300) {
  6. return response;
  7. }
  8. const error = new Error(response.statusText);
  9. error.response = response;
  10. throw error;
  11. }
  12. /**
  13. * 将Response内容转为JSON格式
  14. */
  15. function parseJSON(response) {
  16. return response.json();
  17. }
  18. /**
  19. * 统一拦截接口返回数据的状态,提示错误消息
  20. */
  21. function checkAPIDatas(data) {
  22. console.log('data',data)
  23. if (!data.success) {
  24. const code = data;
  25. }
  26. return data
  27. }
  28. function checkAPIError(err) {
  29. const code = err.response.code;
  30. const status = err.response.status;
  31. // const { url, type, oStatus, statusText } = err.response;
  32. // Message.error(`地址:${url} 类型:${type} 状态:${oStatus} 信息:${statusText}`, 10);
  33. return {
  34. err
  35. };
  36. }
  37. /**
  38. * Requests a URL, returning a promise.
  39. * @param {string} url The URL we want to request
  40. * @param {object} [options] The options we want to pass to "fetch"
  41. * @return {object} An object containing either "data" or "err"
  42. */
  43. const request = async (url, options,callBack) => {
  44. if (options) {
  45. const method = options.method.toUpperCase();
  46. if (method === 'POST' || method === 'PATCH' || method === 'DELETE' || method === 'PUT') {
  47. options.headers = {
  48. 'Content-Type': 'application/json',
  49. 'token': await storage.load({
  50. key: 'token'
  51. })
  52. };
  53. } else {
  54. options.headers = {
  55. 'token': await storage.load({
  56. key: 'token'
  57. })
  58. };
  59. }
  60. }
  61. return fetch(url, options)
  62. .then(checkStatus)
  63. .then(parseJSON)
  64. .then(checkAPIDatas)
  65. .catch(checkAPIError);
  66. }
  67. export default request