request-xhr.js 959 B

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. module.exports = request;
  3. function request(method, url, headers, body, callback) {
  4. if (typeof body === "function") {
  5. callback = body;
  6. body = undefined;
  7. }
  8. if (!callback) {
  9. return request.bind(null, method, url, headers, body);
  10. }
  11. var xhr = new XMLHttpRequest();
  12. xhr.open(method, url, true);
  13. xhr.responseType = "arraybuffer";
  14. Object.keys(headers).forEach(function (name) {
  15. xhr.setRequestHeader(name, headers[name]);
  16. });
  17. xhr.onreadystatechange = function () {
  18. if (xhr.readyState !== 4) return;
  19. var resHeaders = {};
  20. xhr.getAllResponseHeaders().trim().split("\r\n").forEach(function (line) {
  21. var index = line.indexOf(":");
  22. resHeaders[line.substring(0, index).toLowerCase()] = line.substring(index + 1).trim();
  23. });
  24. callback(null, {
  25. statusCode: xhr.status,
  26. headers: resHeaders,
  27. body: xhr.response && new Uint8Array(xhr.response)
  28. });
  29. };
  30. xhr.send(body);
  31. }