fetch.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var each = require('./each');
  2. var defaults = require('./defaults');
  3. var noop = require('./noop');
  4. var has = require('./has');
  5. var root = require('./root');
  6. var Promise = root.Promise;
  7. exports = function(url, options) {
  8. options = options || {};
  9. defaults(options, exports.setting);
  10. return new Promise(function(resolve, reject) {
  11. var xhr = options.xhr();
  12. var headers = options.headers;
  13. var body = options.body;
  14. var timeout = options.timeout;
  15. var abortTimer;
  16. xhr.withCredentials = options.credentials == 'include';
  17. xhr.onload = function() {
  18. clearTimeout(abortTimer);
  19. resolve(getRes(xhr));
  20. };
  21. xhr.onerror = reject;
  22. xhr.open(options.method, url, true);
  23. each(headers, function(val, key) {
  24. xhr.setRequestHeader(key, val);
  25. });
  26. if (timeout > 0) {
  27. setTimeout(function() {
  28. xhr.onload = noop;
  29. xhr.abort();
  30. reject(Error('timeout'));
  31. }, timeout);
  32. }
  33. xhr.send(body);
  34. });
  35. };
  36. var regHeaders = /^(.*?):\s*([\s\S]*?)$/gm;
  37. function getRes(xhr) {
  38. var keys = [];
  39. var all = [];
  40. var headers = {};
  41. var header;
  42. xhr.getAllResponseHeaders().replace(regHeaders, function(m, key, val) {
  43. key = key.toLowerCase();
  44. keys.push(key);
  45. all.push([key, val]);
  46. header = headers[key];
  47. headers[key] = header ? header + ',' + val : val;
  48. });
  49. return {
  50. ok: xhr.status >= 200 && xhr.status < 400,
  51. status: xhr.status,
  52. statusText: xhr.statusText,
  53. url: xhr.responseURL,
  54. clone: function() {
  55. return getRes(xhr);
  56. },
  57. text: function() {
  58. return Promise.resolve(xhr.responseText);
  59. },
  60. json: function() {
  61. return Promise.resolve(xhr.responseText).then(JSON.parse);
  62. },
  63. xml: function() {
  64. return Promise.resolve(xhr.responseXML);
  65. },
  66. blob: function() {
  67. return Promise.resolve(new Blob([xhr.response]));
  68. },
  69. headers: {
  70. keys: function() {
  71. return keys;
  72. },
  73. entries: function() {
  74. return all;
  75. },
  76. get: function(name) {
  77. return headers[name.toLowerCase()];
  78. },
  79. has: function(name) {
  80. return has(headers, name);
  81. }
  82. }
  83. };
  84. }
  85. exports.setting = {
  86. method: 'GET',
  87. headers: {},
  88. timeout: 0,
  89. xhr: function() {
  90. return new XMLHttpRequest();
  91. }
  92. };
  93. module.exports = exports;