request.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. const codeMessage = {
  6. 200: "服务器成功返回请求的数据。",
  7. 201: "新建或修改数据成功。",
  8. 202: "一个请求已经进入后台排队(异步任务)。",
  9. 204: "删除数据成功。",
  10. 400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。",
  11. 401: "用户没有权限(令牌、用户名、密码错误)。",
  12. 403: "用户得到授权,但是访问是被禁止的。",
  13. 404: "发出的请求针对的是不存在的记录,服务器没有进行操作。",
  14. 406: "请求的格式不可得。",
  15. 410: "请求的资源被永久删除,且不会再得到的。",
  16. 422: "当创建一个对象时,发生一个验证错误。",
  17. 500: "服务器发生错误,请检查服务器。",
  18. 502: "网关错误。",
  19. 503: "服务不可用,服务器暂时过载或维护。",
  20. 504: "网关超时。"
  21. };
  22. function checkStatus(response) {
  23. if (response.status >= 200 && response.status < 300) {
  24. return response;
  25. }
  26. const errortext = codeMessage[response.status] || response.message;
  27. const error = new Error(errortext);
  28. error.name = response.status;
  29. error.response = response;
  30. throw error;
  31. }
  32. /**
  33. * Requests a URL, returning a promise.
  34. *
  35. * @param {string} url The URL we want to request
  36. * @param {{method:string,body}} [options] The options we want to pass to "fetch"
  37. * @return {object} An object containing either "data" or "err"
  38. */
  39. export default async function request(url, options) {
  40. const defaultOptions = {
  41. credentials: "include"
  42. };
  43. const newOptions = { ...defaultOptions, ...options };
  44. if (
  45. newOptions.method === "POST" ||
  46. newOptions.method === "PUT" ||
  47. newOptions.method === "DELETE"
  48. ) {
  49. if (!(newOptions.body instanceof FormData)) {
  50. newOptions.headers = {
  51. Accept: "application/json",
  52. "Content-Type": "application/json; charset=utf-8",
  53. ...newOptions.headers
  54. };
  55. newOptions.body = JSON.stringify(newOptions.body);
  56. } else {
  57. // newOptions.body is FormData
  58. newOptions.headers = {
  59. Accept: "application/json",
  60. ...newOptions.headers
  61. };
  62. }
  63. }
  64. const response = await fetch(url, newOptions);
  65. try {
  66. checkStatus(response);
  67. } catch (e) {
  68. if (e.name !== 418) {
  69. router.push({ name: LOGIN_ROUTER });
  70. } else {
  71. throw new Error(e);
  72. }
  73. }
  74. if (newOptions.method === "DELETE" || response.status === 204) {
  75. return response.text();
  76. }
  77. return response.json();
  78. }