index.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export default function(url, options) {
  2. options = options || {};
  3. return new Promise( (resolve, reject) => {
  4. const request = new XMLHttpRequest();
  5. const keys = [];
  6. const all = [];
  7. const headers = {};
  8. const response = () => ({
  9. ok: (request.status/100|0) == 2, // 200-299
  10. statusText: request.statusText,
  11. status: request.status,
  12. url: request.responseURL,
  13. text: () => Promise.resolve(request.responseText),
  14. json: () => Promise.resolve(request.responseText).then(JSON.parse),
  15. blob: () => Promise.resolve(new Blob([request.response])),
  16. clone: response,
  17. headers: {
  18. keys: () => keys,
  19. entries: () => all,
  20. get: n => headers[n.toLowerCase()],
  21. has: n => n.toLowerCase() in headers
  22. }
  23. });
  24. request.open(options.method || 'get', url, true);
  25. request.onload = () => {
  26. request.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, (m, key, value) => {
  27. keys.push(key = key.toLowerCase());
  28. all.push([key, value]);
  29. headers[key] = headers[key] ? `${headers[key]},${value}` : value;
  30. });
  31. resolve(response());
  32. };
  33. request.onerror = reject;
  34. request.withCredentials = options.credentials=='include';
  35. for (const i in options.headers) {
  36. request.setRequestHeader(i, options.headers[i]);
  37. }
  38. request.send(options.body || null);
  39. });
  40. }