request.js 1.5 KB

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