MES手机端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 3 недеља
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. "use strict";
  2. var window = require("global/window")
  3. var isFunction = require("is-function")
  4. var parseHeaders = require("parse-headers")
  5. var xtend = require("xtend")
  6. module.exports = createXHR
  7. // Allow use of default import syntax in TypeScript
  8. module.exports.default = createXHR;
  9. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  10. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  11. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  12. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  13. options = initParams(uri, options, callback)
  14. options.method = method.toUpperCase()
  15. return _createXHR(options)
  16. }
  17. })
  18. function forEachArray(array, iterator) {
  19. for (var i = 0; i < array.length; i++) {
  20. iterator(array[i])
  21. }
  22. }
  23. function isEmpty(obj){
  24. for(var i in obj){
  25. if(obj.hasOwnProperty(i)) return false
  26. }
  27. return true
  28. }
  29. function initParams(uri, options, callback) {
  30. var params = uri
  31. if (isFunction(options)) {
  32. callback = options
  33. if (typeof uri === "string") {
  34. params = {uri:uri}
  35. }
  36. } else {
  37. params = xtend(options, {uri: uri})
  38. }
  39. params.callback = callback
  40. return params
  41. }
  42. function createXHR(uri, options, callback) {
  43. options = initParams(uri, options, callback)
  44. return _createXHR(options)
  45. }
  46. function _createXHR(options) {
  47. if(typeof options.callback === "undefined"){
  48. throw new Error("callback argument missing")
  49. }
  50. var called = false
  51. var callback = function cbOnce(err, response, body){
  52. if(!called){
  53. called = true
  54. options.callback(err, response, body)
  55. }
  56. }
  57. function readystatechange() {
  58. if (xhr.readyState === 4) {
  59. setTimeout(loadFunc, 0)
  60. }
  61. }
  62. function getBody() {
  63. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  64. var body = undefined
  65. if (xhr.response) {
  66. body = xhr.response
  67. } else {
  68. body = xhr.responseText || getXml(xhr)
  69. }
  70. if (isJson) {
  71. try {
  72. body = JSON.parse(body)
  73. } catch (e) {}
  74. }
  75. return body
  76. }
  77. function errorFunc(evt) {
  78. clearTimeout(timeoutTimer)
  79. if(!(evt instanceof Error)){
  80. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  81. }
  82. evt.statusCode = 0
  83. return callback(evt, failureResponse)
  84. }
  85. // will load the data & process the response in a special response object
  86. function loadFunc() {
  87. if (aborted) return
  88. var status
  89. clearTimeout(timeoutTimer)
  90. if(options.useXDR && xhr.status===undefined) {
  91. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  92. status = 200
  93. } else {
  94. status = (xhr.status === 1223 ? 204 : xhr.status)
  95. }
  96. var response = failureResponse
  97. var err = null
  98. if (status !== 0){
  99. response = {
  100. body: getBody(),
  101. statusCode: status,
  102. method: method,
  103. headers: {},
  104. url: uri,
  105. rawRequest: xhr
  106. }
  107. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  108. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  109. }
  110. } else {
  111. err = new Error("Internal XMLHttpRequest Error")
  112. }
  113. return callback(err, response, response.body)
  114. }
  115. var xhr = options.xhr || null
  116. if (!xhr) {
  117. if (options.cors || options.useXDR) {
  118. xhr = new createXHR.XDomainRequest()
  119. }else{
  120. xhr = new createXHR.XMLHttpRequest()
  121. }
  122. }
  123. var key
  124. var aborted
  125. var uri = xhr.url = options.uri || options.url
  126. var method = xhr.method = options.method || "GET"
  127. var body = options.body || options.data
  128. var headers = xhr.headers = options.headers || {}
  129. var sync = !!options.sync
  130. var isJson = false
  131. var timeoutTimer
  132. var failureResponse = {
  133. body: undefined,
  134. headers: {},
  135. statusCode: 0,
  136. method: method,
  137. url: uri,
  138. rawRequest: xhr
  139. }
  140. if ("json" in options && options.json !== false) {
  141. isJson = true
  142. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  143. if (method !== "GET" && method !== "HEAD") {
  144. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  145. body = JSON.stringify(options.json === true ? body : options.json)
  146. }
  147. }
  148. xhr.onreadystatechange = readystatechange
  149. xhr.onload = loadFunc
  150. xhr.onerror = errorFunc
  151. // IE9 must have onprogress be set to a unique function.
  152. xhr.onprogress = function () {
  153. // IE must die
  154. }
  155. xhr.onabort = function(){
  156. aborted = true;
  157. }
  158. xhr.ontimeout = errorFunc
  159. xhr.open(method, uri, !sync, options.username, options.password)
  160. //has to be after open
  161. if(!sync) {
  162. xhr.withCredentials = !!options.withCredentials
  163. }
  164. // Cannot set timeout with sync request
  165. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  166. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  167. if (!sync && options.timeout > 0 ) {
  168. timeoutTimer = setTimeout(function(){
  169. if (aborted) return
  170. aborted = true//IE9 may still call readystatechange
  171. xhr.abort("timeout")
  172. var e = new Error("XMLHttpRequest timeout")
  173. e.code = "ETIMEDOUT"
  174. errorFunc(e)
  175. }, options.timeout )
  176. }
  177. if (xhr.setRequestHeader) {
  178. for(key in headers){
  179. if(headers.hasOwnProperty(key)){
  180. xhr.setRequestHeader(key, headers[key])
  181. }
  182. }
  183. } else if (options.headers && !isEmpty(options.headers)) {
  184. throw new Error("Headers cannot be set on an XDomainRequest object")
  185. }
  186. if ("responseType" in options) {
  187. xhr.responseType = options.responseType
  188. }
  189. if ("beforeSend" in options &&
  190. typeof options.beforeSend === "function"
  191. ) {
  192. options.beforeSend(xhr)
  193. }
  194. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  195. // XMLHttpRequest spec says to pass null as body to indicate no body
  196. // See https://github.com/naugtur/xhr/issues/100.
  197. xhr.send(body || null)
  198. return xhr
  199. }
  200. function getXml(xhr) {
  201. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  202. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  203. try {
  204. if (xhr.responseType === "document") {
  205. return xhr.responseXML
  206. }
  207. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  208. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  209. return xhr.responseXML
  210. }
  211. } catch (e) {}
  212. return null
  213. }
  214. function noop() {}