OMGUtils.js 769 B

123456789101112131415161718192021222324252627282930313233
  1. const fetchHeaders = {
  2. 'Accept': 'text/html',
  3. 'Content-Type': 'text/html',
  4. 'X-Requested-With': 'XMLHttpRequest',
  5. 'Cache-Control': 'no-cache',
  6. 'Pragma': 'no-cache',
  7. 'Expires': '0'
  8. };
  9. /**
  10. * Make an AJAX request.
  11. *
  12. * If error, catch return a promise error object:
  13. *
  14. * .catch(err => alert(`${err.url}\n\n${err.status} (${err.statusText})`));
  15. *
  16. * @param url URL of RESTful api to call
  17. * @param options the fetch() options
  18. * @returns {Promise<Response | never>}
  19. */
  20. export function AjaxReq(url, options) {
  21. let defaults = {headers: fetchHeaders};
  22. // Extend default options
  23. Object.assign(defaults, options);
  24. return fetch(url, defaults)
  25. .then(resp => {
  26. if (resp.status === 200)
  27. return resp.json();
  28. else
  29. return Promise.reject(resp);
  30. });
  31. }