request.js 2.0 KB

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