Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. node-fetch
  2. ==========
  3. [![npm version][npm-image]][npm-url]
  4. [![build status][travis-image]][travis-url]
  5. [![coverage status][codecov-image]][codecov-url]
  6. A light-weight module that brings `window.fetch` to Node.js
  7. # Motivation
  8. Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `Fetch` API directly? Hence `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
  9. See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
  10. # Features
  11. - Stay consistent with `window.fetch` API.
  12. - Make conscious trade-off when following [whatwg fetch spec](https://fetch.spec.whatwg.org/) and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known difference.
  13. - Use native promise, but allow substituting it with [insert your favorite promise library].
  14. - Use native stream for body, on both request and response.
  15. - Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
  16. - Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md) for troubleshooting.
  17. # Difference from client-side fetch
  18. - See [Known Differences](https://github.com/bitinn/node-fetch/blob/master/LIMITS.md) for details.
  19. - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
  20. - Pull requests are welcomed too!
  21. # Install
  22. `npm install node-fetch --save`
  23. # Usage
  24. ```javascript
  25. var fetch = require('node-fetch');
  26. // if you are on node v0.10, set a Promise library first, eg.
  27. // fetch.Promise = require('bluebird');
  28. // plain text or html
  29. fetch('https://github.com/')
  30. .then(function(res) {
  31. return res.text();
  32. }).then(function(body) {
  33. console.log(body);
  34. });
  35. // json
  36. fetch('https://api.github.com/users/github')
  37. .then(function(res) {
  38. return res.json();
  39. }).then(function(json) {
  40. console.log(json);
  41. });
  42. // catching network error
  43. // 3xx-5xx responses are NOT network errors, and should be handled in then()
  44. // you only need one catch() at the end of your promise chain
  45. fetch('http://domain.invalid/')
  46. .catch(function(err) {
  47. console.log(err);
  48. });
  49. // stream
  50. // the node.js way is to use stream when possible
  51. fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
  52. .then(function(res) {
  53. var dest = fs.createWriteStream('./octocat.png');
  54. res.body.pipe(dest);
  55. });
  56. // buffer
  57. // if you prefer to cache binary data in full, use buffer()
  58. // note that buffer() is a node-fetch only API
  59. var fileType = require('file-type');
  60. fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
  61. .then(function(res) {
  62. return res.buffer();
  63. }).then(function(buffer) {
  64. fileType(buffer);
  65. });
  66. // meta
  67. fetch('https://github.com/')
  68. .then(function(res) {
  69. console.log(res.ok);
  70. console.log(res.status);
  71. console.log(res.statusText);
  72. console.log(res.headers.raw());
  73. console.log(res.headers.get('content-type'));
  74. });
  75. // post
  76. fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })
  77. .then(function(res) {
  78. return res.json();
  79. }).then(function(json) {
  80. console.log(json);
  81. });
  82. // post with stream from resumer
  83. var resumer = require('resumer');
  84. var stream = resumer().queue('a=1').end();
  85. fetch('http://httpbin.org/post', { method: 'POST', body: stream })
  86. .then(function(res) {
  87. return res.json();
  88. }).then(function(json) {
  89. console.log(json);
  90. });
  91. // post with form-data (detect multipart)
  92. var FormData = require('form-data');
  93. var form = new FormData();
  94. form.append('a', 1);
  95. fetch('http://httpbin.org/post', { method: 'POST', body: form })
  96. .then(function(res) {
  97. return res.json();
  98. }).then(function(json) {
  99. console.log(json);
  100. });
  101. // post with form-data (custom headers)
  102. // note that getHeaders() is non-standard API
  103. var FormData = require('form-data');
  104. var form = new FormData();
  105. form.append('a', 1);
  106. fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
  107. .then(function(res) {
  108. return res.json();
  109. }).then(function(json) {
  110. console.log(json);
  111. });
  112. // node 0.12+, yield with co
  113. var co = require('co');
  114. co(function *() {
  115. var res = yield fetch('https://api.github.com/users/github');
  116. var json = yield res.json();
  117. console.log(res);
  118. });
  119. ```
  120. See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
  121. # API
  122. ## fetch(url, options)
  123. Returns a `Promise`
  124. ### Url
  125. Should be an absolute url, eg `http://example.com/`
  126. ### Options
  127. default values are shown, note that only `method`, `headers`, `redirect` and `body` are allowed in `window.fetch`, others are node.js extensions.
  128. ```
  129. {
  130. method: 'GET'
  131. , headers: {} // request header. format {a:'1'} or {b:['1','2','3']}
  132. , redirect: 'follow' // set to `manual` to extract redirect headers, `error` to reject redirect
  133. , follow: 20 // maximum redirect count. 0 to not follow redirect
  134. , timeout: 0 // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)
  135. , compress: true // support gzip/deflate content encoding. false to disable
  136. , size: 0 // maximum response body size in bytes. 0 to disable
  137. , body: empty // request body. can be a string, buffer, readable stream
  138. , agent: null // http.Agent instance, allows custom proxy, certificate etc.
  139. }
  140. ```
  141. # License
  142. MIT
  143. # Acknowledgement
  144. Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
  145. [npm-image]: https://img.shields.io/npm/v/node-fetch.svg?style=flat-square
  146. [npm-url]: https://www.npmjs.com/package/node-fetch
  147. [travis-image]: https://img.shields.io/travis/bitinn/node-fetch.svg?style=flat-square
  148. [travis-url]: https://travis-ci.org/bitinn/node-fetch
  149. [codecov-image]: https://img.shields.io/codecov/c/github/bitinn/node-fetch.svg?style=flat-square
  150. [codecov-url]: https://codecov.io/gh/bitinn/node-fetch