request.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import fetch from 'dva/fetch';
  2. import { notification } from 'antd';
  3. function checkStatus(response) {
  4. if (response.status >= 200 && response.status < 300) {
  5. return response;
  6. }
  7. const error = new Error(response.statusText);
  8. error.response = response;
  9. throw error;
  10. }
  11. /**
  12. * Requests a URL, returning a promise.
  13. *
  14. * @param {string} url The URL we want to request
  15. * @param {object} [options] The options we want to pass to "fetch"
  16. * @return {object} An object containing either "data" or "err"
  17. */
  18. export default function request(url, options) {
  19. const defaultOptions = {
  20. credentials: 'include',
  21. };
  22. const newOptions = { ...defaultOptions, ...options };
  23. if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
  24. newOptions.headers = {
  25. Accept: 'application/json',
  26. 'Content-Type': 'application/json; charset=utf-8',
  27. ...newOptions.headers,
  28. };
  29. newOptions.body = JSON.stringify(newOptions.body);
  30. }
  31. return fetch(url, newOptions)
  32. .then(checkStatus)
  33. .then(response => response.json())
  34. .catch((error) => {
  35. if (error.code) {
  36. notification.error({
  37. message: error.name,
  38. description: error.message,
  39. });
  40. }
  41. if ('stack' in error && 'message' in error) {
  42. notification.error({
  43. message: `请求错误: ${url}`,
  44. description: error.message,
  45. });
  46. }
  47. });
  48. }