request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // ant-design-pro request.js file with MIT license
  2. import "whatwg-fetch";
  3. import router from "@/router";
  4. import { LOGIN } from "@/router/name";
  5. /**
  6. * @description error
  7. * @typedef {Object} StatusException
  8. * @property {string} name status code
  9. * @property {string} message 消息
  10. * @property {{code:string,message:string,body:{code:number,message:string}}} response 返回值
  11. */
  12. /**
  13. * 判断是否抛异常
  14. * @param response
  15. * @returns {*}
  16. * @throws StatusException
  17. */
  18. const checkStatus = async response => {
  19. if (response.status >= 200 && response.status < 300) {
  20. return response;
  21. }
  22. let responseBody = {};
  23. try {
  24. responseBody = await response.json();
  25. } catch (e) {
  26. console.log(e);
  27. }
  28. console.log(responseBody);
  29. const error = new Error();
  30. error.name = response.status;
  31. error.message = responseBody.message;
  32. error.body = responseBody;
  33. throw error;
  34. };
  35. /**
  36. * Requests a URL, returning a promise.
  37. *
  38. * @param {string} url The URL we want to request
  39. * @param {{method:string,body}} [options] The options we want to pass to "fetch"
  40. * @return {Promise<*>} An object containing either "data" or "err"
  41. * @throws StatusException
  42. */
  43. export default async function request(url, options) {
  44. const defaultOptions = {
  45. credentials: "include"
  46. };
  47. const newOptions = { ...defaultOptions, ...options };
  48. if (
  49. newOptions.method === "POST" ||
  50. newOptions.method === "PUT" ||
  51. newOptions.method === "DELETE"
  52. ) {
  53. if (!(newOptions.body instanceof FormData)) {
  54. newOptions.headers = {
  55. Accept: "application/json",
  56. "Content-Type": "application/json; charset=utf-8",
  57. ...newOptions.headers
  58. };
  59. newOptions.body = JSON.stringify(newOptions.body);
  60. } else {
  61. // newOptions.body is FormData
  62. newOptions.headers = {
  63. Accept: "application/json",
  64. ...newOptions.headers
  65. };
  66. }
  67. }
  68. const response = await fetch(url, newOptions);
  69. try {
  70. await checkStatus(response);
  71. } catch (e) {
  72. if (e.name === 401) {
  73. router.push({ name: LOGIN });
  74. } else {
  75. throw e;
  76. }
  77. }
  78. if (newOptions.method === "DELETE" || response.status === 204) {
  79. return response.text();
  80. }
  81. const Authorization = await response.headers.get("Authorization");
  82. const body = await response.json();
  83. const header = {
  84. Authorization
  85. };
  86. return { ...body, _header: header };
  87. }