request.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import * as capability from './capability';
  2. import {inherits} from 'util';
  3. import {IncomingMessage, readyStates as rStates} from './response';
  4. import {Writable} from 'stream';
  5. import toArrayBuffer from './to-arraybuffer';
  6. function decideMode(preferBinary, useFetch) {
  7. if (capability.hasFetch && useFetch) {
  8. return 'fetch'
  9. } else if (capability.mozchunkedarraybuffer) {
  10. return 'moz-chunked-arraybuffer'
  11. } else if (capability.msstream) {
  12. return 'ms-stream'
  13. } else if (capability.arraybuffer && preferBinary) {
  14. return 'arraybuffer'
  15. } else if (capability.vbArray && preferBinary) {
  16. return 'text:vbarray'
  17. } else {
  18. return 'text'
  19. }
  20. }
  21. export default ClientRequest;
  22. function ClientRequest(opts) {
  23. var self = this
  24. Writable.call(self)
  25. self._opts = opts
  26. self._body = []
  27. self._headers = {}
  28. if (opts.auth)
  29. self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
  30. Object.keys(opts.headers).forEach(function(name) {
  31. self.setHeader(name, opts.headers[name])
  32. })
  33. var preferBinary
  34. var useFetch = true
  35. if (opts.mode === 'disable-fetch') {
  36. // If the use of XHR should be preferred and includes preserving the 'content-type' header
  37. useFetch = false
  38. preferBinary = true
  39. } else if (opts.mode === 'prefer-streaming') {
  40. // If streaming is a high priority but binary compatibility and
  41. // the accuracy of the 'content-type' header aren't
  42. preferBinary = false
  43. } else if (opts.mode === 'allow-wrong-content-type') {
  44. // If streaming is more important than preserving the 'content-type' header
  45. preferBinary = !capability.overrideMimeType
  46. } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
  47. // Use binary if text streaming may corrupt data or the content-type header, or for speed
  48. preferBinary = true
  49. } else {
  50. throw new Error('Invalid value for opts.mode')
  51. }
  52. self._mode = decideMode(preferBinary, useFetch)
  53. self.on('finish', function() {
  54. self._onFinish()
  55. })
  56. }
  57. inherits(ClientRequest, Writable)
  58. // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
  59. var unsafeHeaders = [
  60. 'accept-charset',
  61. 'accept-encoding',
  62. 'access-control-request-headers',
  63. 'access-control-request-method',
  64. 'connection',
  65. 'content-length',
  66. 'cookie',
  67. 'cookie2',
  68. 'date',
  69. 'dnt',
  70. 'expect',
  71. 'host',
  72. 'keep-alive',
  73. 'origin',
  74. 'referer',
  75. 'te',
  76. 'trailer',
  77. 'transfer-encoding',
  78. 'upgrade',
  79. 'user-agent',
  80. 'via'
  81. ]
  82. ClientRequest.prototype.setHeader = function(name, value) {
  83. var self = this
  84. var lowerName = name.toLowerCase()
  85. // This check is not necessary, but it prevents warnings from browsers about setting unsafe
  86. // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
  87. // http-browserify did it, so I will too.
  88. if (unsafeHeaders.indexOf(lowerName) !== -1)
  89. return
  90. self._headers[lowerName] = {
  91. name: name,
  92. value: value
  93. }
  94. }
  95. ClientRequest.prototype.getHeader = function(name) {
  96. var self = this
  97. return self._headers[name.toLowerCase()].value
  98. }
  99. ClientRequest.prototype.removeHeader = function(name) {
  100. var self = this
  101. delete self._headers[name.toLowerCase()]
  102. }
  103. ClientRequest.prototype._onFinish = function() {
  104. var self = this
  105. if (self._destroyed)
  106. return
  107. var opts = self._opts
  108. var headersObj = self._headers
  109. var body
  110. if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
  111. if (capability.blobConstructor()) {
  112. body = new global.Blob(self._body.map(function(buffer) {
  113. return toArrayBuffer(buffer)
  114. }), {
  115. type: (headersObj['content-type'] || {}).value || ''
  116. })
  117. } else {
  118. // get utf8 string
  119. body = Buffer.concat(self._body).toString()
  120. }
  121. }
  122. if (self._mode === 'fetch') {
  123. var headers = Object.keys(headersObj).map(function(name) {
  124. return [headersObj[name].name, headersObj[name].value]
  125. })
  126. global.fetch(self._opts.url, {
  127. method: self._opts.method,
  128. headers: headers,
  129. body: body,
  130. mode: 'cors',
  131. credentials: opts.withCredentials ? 'include' : 'same-origin'
  132. }).then(function(response) {
  133. self._fetchResponse = response
  134. self._connect()
  135. }, function(reason) {
  136. self.emit('error', reason)
  137. })
  138. } else {
  139. var xhr = self._xhr = new global.XMLHttpRequest()
  140. try {
  141. xhr.open(self._opts.method, self._opts.url, true)
  142. } catch (err) {
  143. process.nextTick(function() {
  144. self.emit('error', err)
  145. })
  146. return
  147. }
  148. // Can't set responseType on really old browsers
  149. if ('responseType' in xhr)
  150. xhr.responseType = self._mode.split(':')[0]
  151. if ('withCredentials' in xhr)
  152. xhr.withCredentials = !!opts.withCredentials
  153. if (self._mode === 'text' && 'overrideMimeType' in xhr)
  154. xhr.overrideMimeType('text/plain; charset=x-user-defined')
  155. Object.keys(headersObj).forEach(function(name) {
  156. xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
  157. })
  158. self._response = null
  159. xhr.onreadystatechange = function() {
  160. switch (xhr.readyState) {
  161. case rStates.LOADING:
  162. case rStates.DONE:
  163. self._onXHRProgress()
  164. break
  165. }
  166. }
  167. // Necessary for streaming in Firefox, since xhr.response is ONLY defined
  168. // in onprogress, not in onreadystatechange with xhr.readyState = 3
  169. if (self._mode === 'moz-chunked-arraybuffer') {
  170. xhr.onprogress = function() {
  171. self._onXHRProgress()
  172. }
  173. }
  174. xhr.onerror = function() {
  175. if (self._destroyed)
  176. return
  177. self.emit('error', new Error('XHR error'))
  178. }
  179. try {
  180. xhr.send(body)
  181. } catch (err) {
  182. process.nextTick(function() {
  183. self.emit('error', err)
  184. })
  185. return
  186. }
  187. }
  188. }
  189. /**
  190. * Checks if xhr.status is readable and non-zero, indicating no error.
  191. * Even though the spec says it should be available in readyState 3,
  192. * accessing it throws an exception in IE8
  193. */
  194. function statusValid(xhr) {
  195. try {
  196. var status = xhr.status
  197. return (status !== null && status !== 0)
  198. } catch (e) {
  199. return false
  200. }
  201. }
  202. ClientRequest.prototype._onXHRProgress = function() {
  203. var self = this
  204. if (!statusValid(self._xhr) || self._destroyed)
  205. return
  206. if (!self._response)
  207. self._connect()
  208. self._response._onXHRProgress()
  209. }
  210. ClientRequest.prototype._connect = function() {
  211. var self = this
  212. if (self._destroyed)
  213. return
  214. self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
  215. self.emit('response', self._response)
  216. }
  217. ClientRequest.prototype._write = function(chunk, encoding, cb) {
  218. var self = this
  219. self._body.push(chunk)
  220. cb()
  221. }
  222. ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() {
  223. var self = this
  224. self._destroyed = true
  225. if (self._response)
  226. self._response._destroyed = true
  227. if (self._xhr)
  228. self._xhr.abort()
  229. // Currently, there isn't a way to truly abort a fetch.
  230. // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
  231. }
  232. ClientRequest.prototype.end = function(data, encoding, cb) {
  233. var self = this
  234. if (typeof data === 'function') {
  235. cb = data
  236. data = undefined
  237. }
  238. Writable.prototype.end.call(self, data, encoding, cb)
  239. }
  240. ClientRequest.prototype.flushHeaders = function() {}
  241. ClientRequest.prototype.setTimeout = function() {}
  242. ClientRequest.prototype.setNoDelay = function() {}
  243. ClientRequest.prototype.setSocketKeepAlive = function() {}