request.js 737 B

123456789101112131415161718192021222324252627282930
  1. import fetch from 'dva/fetch';
  2. function parseJSON(response) {
  3. return response.json();
  4. }
  5. function checkStatus(response) {
  6. if (response.status >= 200 && response.status < 300) {
  7. return response;
  8. }
  9. const error = new Error(response.statusText);
  10. error.response = response;
  11. throw error;
  12. }
  13. /**
  14. * Requests a URL, returning a promise.
  15. *
  16. * @param {string} url The URL we want to request
  17. * @param {object} [options] The options we want to pass to "fetch"
  18. * @return {object} An object containing either "data" or "err"
  19. */
  20. export default function request(url, options) {
  21. return fetch(url, options)
  22. .then(checkStatus)
  23. .then(parseJSON)
  24. .then(data => ({ data }))
  25. .catch(err => ({ err }));
  26. }