| 1 |
// Copyright 2011 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
|
| 16 |
/** |
| 17 |
* @fileoverview Offered as an alternative to XhrIo as a way for making requests |
| 18 |
* via XMLHttpRequest. Instead of mirroring the XHR interface and exposing |
| 19 |
* events, results are used as a way to pass a "promise" of the response to |
| 20 |
* interested parties. |
| 21 |
* |
| 22 |
*/ |
| 23 |
|
| 24 |
goog.provide('goog.labs.net.xhr'); |
| 25 |
goog.provide('goog.labs.net.xhr.Error'); |
| 26 |
goog.provide('goog.labs.net.xhr.HttpError'); |
| 27 |
goog.provide('goog.labs.net.xhr.Options'); |
| 28 |
goog.provide('goog.labs.net.xhr.PostData'); |
| 29 |
goog.provide('goog.labs.net.xhr.ResponseType'); |
| 30 |
goog.provide('goog.labs.net.xhr.TimeoutError'); |
| 31 |
|
| 32 |
goog.require('goog.Promise'); |
| 33 |
goog.require('goog.asserts'); |
| 34 |
goog.require('goog.debug.Error'); |
| 35 |
goog.require('goog.net.HttpStatus'); |
| 36 |
goog.require('goog.net.XmlHttp'); |
| 37 |
goog.require('goog.object'); |
| 38 |
goog.require('goog.string'); |
| 39 |
goog.require('goog.uri.utils'); |
| 40 |
goog.require('goog.userAgent'); |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
goog.scope(function() { |
| 45 |
var userAgent = goog.userAgent; |
| 46 |
var xhr = goog.labs.net.xhr; |
| 47 |
var HttpStatus = goog.net.HttpStatus; |
| 48 |
|
| 49 |
|
| 50 |
/** |
| 51 |
* Configuration options for an XMLHttpRequest. |
| 52 |
* - headers: map of header key/value pairs. |
| 53 |
* - timeoutMs: number of milliseconds after which the request will be timed |
| 54 |
* out by the client. Default is to allow the browser to handle timeouts. |
| 55 |
* - withCredentials: whether user credentials are to be included in a |
| 56 |
* cross-origin request. See: |
| 57 |
* http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute |
| 58 |
* - mimeType: allows the caller to override the content-type and charset for |
| 59 |
* the request. See: |
| 60 |
* http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-overridemimetype |
| 61 |
* - responseType: may be set to change the response type to an arraybuffer or |
| 62 |
* blob for downloading binary data. See: |
| 63 |
* http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-responsetype] |
| 64 |
* - xmlHttpFactory: allows the caller to override the factory used to create |
| 65 |
* XMLHttpRequest objects. |
| 66 |
* - xssiPrefix: Prefix used for protecting against XSSI attacks, which should |
| 67 |
* be removed before parsing the response as JSON. |
| 68 |
* |
| 69 |
* @typedef {{ |
| 70 |
* headers: (Object<string>|undefined), |
| 71 |
* mimeType: (string|undefined), |
| 72 |
* responseType: (xhr.ResponseType|undefined), |
| 73 |
* timeoutMs: (number|undefined), |
| 74 |
* withCredentials: (boolean|undefined), |
| 75 |
* xmlHttpFactory: (goog.net.XmlHttpFactory|undefined), |
| 76 |
* xssiPrefix: (string|undefined) |
| 77 |
* }} |
| 78 |
*/ |
| 79 |
xhr.Options; |
| 80 |
|
| 81 |
|
| 82 |
/** |
| 83 |
* Defines the types that are allowed as post data. |
| 84 |
* @typedef {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string|undefined)} |
| 85 |
*/ |
| 86 |
xhr.PostData; |
| 87 |
|
| 88 |
|
| 89 |
/** |
| 90 |
* The Content-Type HTTP header name. |
| 91 |
* @type {string} |
| 92 |
*/ |
| 93 |
xhr.CONTENT_TYPE_HEADER = 'Content-Type'; |
| 94 |
|
| 95 |
|
| 96 |
/** |
| 97 |
* The Content-Type HTTP header value for a url-encoded form. |
| 98 |
* @type {string} |
| 99 |
*/ |
| 100 |
xhr.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; |
| 101 |
|
| 102 |
|
| 103 |
/** |
| 104 |
* Supported data types for the responseType field. |
| 105 |
* See: http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-response |
| 106 |
* @enum {string} |
| 107 |
*/ |
| 108 |
xhr.ResponseType = { |
| 109 |
ARRAYBUFFER: 'arraybuffer', |
| 110 |
BLOB: 'blob', |
| 111 |
DOCUMENT: 'document', |
| 112 |
JSON: 'json', |
| 113 |
TEXT: 'text' |
| 114 |
}; |
| 115 |
|
| 116 |
|
| 117 |
/** |
| 118 |
* Sends a get request, returning a promise that will be resolved |
| 119 |
* with the response text once the request completes. |
| 120 |
* |
| 121 |
* @param {string} url The URL to request. |
| 122 |
* @param {xhr.Options=} opt_options Configuration options for the request. |
| 123 |
* @return {!goog.Promise<string>} A promise that will be resolved with the |
| 124 |
* response text once the request completes. |
| 125 |
*/ |
| 126 |
xhr.get = function(url, opt_options) { |
| 127 |
return xhr.send('GET', url, null, opt_options).then(function(request) { |
| 128 |
return request.responseText; |
| 129 |
}); |
| 130 |
}; |
| 131 |
|
| 132 |
|
| 133 |
/** |
| 134 |
* Sends a post request, returning a promise that will be resolved |
| 135 |
* with the response text once the request completes. |
| 136 |
* |
| 137 |
* @param {string} url The URL to request. |
| 138 |
* @param {xhr.PostData} data The body of the post request. |
| 139 |
* @param {xhr.Options=} opt_options Configuration options for the request. |
| 140 |
* @return {!goog.Promise<string>} A promise that will be resolved with the |
| 141 |
* response text once the request completes. |
| 142 |
*/ |
| 143 |
xhr.post = function(url, data, opt_options) { |
| 144 |
return xhr.send('POST', url, data, opt_options).then(function(request) { |
| 145 |
return request.responseText; |
| 146 |
}); |
| 147 |
}; |
| 148 |
|
| 149 |
|
| 150 |
/** |
| 151 |
* Sends a get request, returning a promise that will be resolved with |
| 152 |
* the parsed response text once the request completes. |
| 153 |
* |
| 154 |
* @param {string} url The URL to request. |
| 155 |
* @param {xhr.Options=} opt_options Configuration options for the request. |
| 156 |
* @return {!goog.Promise<Object>} A promise that will be resolved with the |
| 157 |
* response JSON once the request completes. |
| 158 |
*/ |
| 159 |
xhr.getJson = function(url, opt_options) { |
| 160 |
return xhr.send('GET', url, null, opt_options).then(function(request) { |
| 161 |
return xhr.parseJson_(request.responseText, opt_options); |
| 162 |
}); |
| 163 |
}; |
| 164 |
|
| 165 |
|
| 166 |
/** |
| 167 |
* Sends a get request, returning a promise that will be resolved with the |
| 168 |
* response as a Blob. |
| 169 |
* |
| 170 |
* @param {string} url The URL to request. |
| 171 |
* @param {xhr.Options=} opt_options Configuration options for the request. If |
| 172 |
* responseType is set, it will be ignored for this request. |
| 173 |
* @return {!goog.Promise<!Blob>} A promise that will be resolved with an |
| 174 |
* immutable Blob representing the file once the request completes. |
| 175 |
*/ |
| 176 |
xhr.getBlob = function(url, opt_options) { |
| 177 |
goog.asserts.assert( |
| 178 |
'Blob' in goog.global, 'getBlob is not supported in this browser.'); |
| 179 |
|
| 180 |
var options = opt_options ? goog.object.clone(opt_options) : {}; |
| 181 |
options.responseType = xhr.ResponseType.BLOB; |
| 182 |
|
| 183 |
return xhr.send('GET', url, null, options).then(function(request) { |
| 184 |
return /** @type {!Blob} */ (request.response); |
| 185 |
}); |
| 186 |
}; |
| 187 |
|
| 188 |
|
| 189 |
/** |
| 190 |
* Sends a get request, returning a promise that will be resolved with the |
| 191 |
* response as an array of bytes. |
| 192 |
* |
| 193 |
* Supported in all XMLHttpRequest level 2 browsers, as well as IE9. IE8 and |
| 194 |
* earlier are not supported. |
| 195 |
* |
| 196 |
* @param {string} url The URL to request. |
| 197 |
* @param {xhr.Options=} opt_options Configuration options for the request. If |
| 198 |
* responseType is set, it will be ignored for this request. |
| 199 |
* @return {!goog.Promise<!Uint8Array|!Array<number>>} A promise that will be |
| 200 |
* resolved with an array of bytes once the request completes. |
| 201 |
*/ |
| 202 |
xhr.getBytes = function(url, opt_options) { |
| 203 |
goog.asserts.assert( |
| 204 |
!userAgent.IE || userAgent.isDocumentModeOrHigher(9), |
| 205 |
'getBytes is not supported in this browser.'); |
| 206 |
|
| 207 |
var options = opt_options ? goog.object.clone(opt_options) : {}; |
| 208 |
options.responseType = xhr.ResponseType.ARRAYBUFFER; |
| 209 |
|
| 210 |
return xhr.send('GET', url, null, options).then(function(request) { |
| 211 |
// Use the ArrayBuffer response in browsers that support XMLHttpRequest2. |
| 212 |
// This covers nearly all modern browsers: http://caniuse.com/xhr2 |
| 213 |
if (request.response) { |
| 214 |
return new Uint8Array(/** @type {!ArrayBuffer} */ (request.response)); |
| 215 |
} |
| 216 |
|
| 217 |
// Fallback for IE9: the response may be accessed as an array of bytes with |
| 218 |
// the non-standard responseBody property, which can only be accessed as a |
| 219 |
// VBArray. IE7 and IE8 require significant amounts of VBScript to extract |
| 220 |
// the bytes. |
| 221 |
// See: http://stackoverflow.com/questions/1919972/ |
| 222 |
if (goog.global['VBArray']) { |
| 223 |
return new goog.global['VBArray'](request['responseBody']).toArray(); |
| 224 |
} |
| 225 |
|
| 226 |
// Nearly all common browsers are covered by the cases above. If downloading |
| 227 |
// binary files in older browsers is necessary, the MDN article "Sending and |
| 228 |
// Receiving Binary Data" provides techniques that may work with |
| 229 |
// XMLHttpRequest level 1 browsers: http://goo.gl/7lEuGN |
| 230 |
throw new xhr.Error( |
| 231 |
'getBytes is not supported in this browser.', url, request); |
| 232 |
}); |
| 233 |
}; |
| 234 |
|
| 235 |
|
| 236 |
/** |
| 237 |
* Sends a post request, returning a promise that will be resolved with |
| 238 |
* the parsed response text once the request completes. |
| 239 |
* |
| 240 |
* @param {string} url The URL to request. |
| 241 |
* @param {xhr.PostData} data The body of the post request. |
| 242 |
* @param {xhr.Options=} opt_options Configuration options for the request. |
| 243 |
* @return {!goog.Promise<Object>} A promise that will be resolved with the |
| 244 |
* response JSON once the request completes. |
| 245 |
*/ |
| 246 |
xhr.postJson = function(url, data, opt_options) { |
| 247 |
return xhr.send('POST', url, data, opt_options).then(function(request) { |
| 248 |
return xhr.parseJson_(request.responseText, opt_options); |
| 249 |
}); |
| 250 |
}; |
| 251 |
|
| 252 |
|
| 253 |
/** |
| 254 |
* Sends a request, returning a promise that will be resolved |
| 255 |
* with the XHR object once the request completes. |
| 256 |
* |
| 257 |
* If content type hasn't been set in opt_options headers, and hasn't been |
| 258 |
* explicitly set to null, default to form-urlencoded/UTF8 for POSTs. |
| 259 |
* |
| 260 |
* @param {string} method The HTTP method for the request. |
| 261 |
* @param {string} url The URL to request. |
| 262 |
* @param {xhr.PostData} data The body of the post request. |
| 263 |
* @param {xhr.Options=} opt_options Configuration options for the request. |
| 264 |
* @return {!goog.Promise<!goog.net.XhrLike.OrNative>} A promise that will be |
| 265 |
* resolved with the XHR object once the request completes. |
| 266 |
*/ |
| 267 |
xhr.send = function(method, url, data, opt_options) { |
| 268 |
var options = opt_options || {}; |
| 269 |
var request = options.xmlHttpFactory ? |
| 270 |
options.xmlHttpFactory.createInstance() : |
| 271 |
goog.net.XmlHttp(); |
| 272 |
|
| 273 |
var result = new goog.Promise(function(resolve, reject) { |
| 274 |
var timer; |
| 275 |
|
| 276 |
try { |
| 277 |
request.open(method, url, true); |
| 278 |
} catch (e) { |
| 279 |
// XMLHttpRequest.open may throw when 'open' is called, for example, IE7 |
| 280 |
// throws "Access Denied" for cross-origin requests. |
| 281 |
reject(new xhr.Error('Error opening XHR: ' + e.message, url, request)); |
| 282 |
} |
| 283 |
|
| 284 |
// So sad that IE doesn't support onload and onerror. |
| 285 |
request.onreadystatechange = function() { |
| 286 |
if (request.readyState == goog.net.XmlHttp.ReadyState.COMPLETE) { |
| 287 |
goog.global.clearTimeout(timer); |
| 288 |
// Note: When developing locally, XHRs to file:// schemes return |
| 289 |
// a status code of 0. We mark that case as a success too. |
| 290 |
if (HttpStatus.isSuccess(request.status) || |
| 291 |
request.status === 0 && !xhr.isEffectiveSchemeHttp_(url)) { |
| 292 |
resolve(request); |
| 293 |
} else { |
| 294 |
reject(new xhr.HttpError(request.status, url, request)); |
| 295 |
} |
| 296 |
} |
| 297 |
}; |
| 298 |
request.onerror = function() { |
| 299 |
reject(new xhr.Error('Network error', url, request)); |
| 300 |
}; |
| 301 |
|
| 302 |
// Set the headers. |
| 303 |
var contentType; |
| 304 |
if (options.headers) { |
| 305 |
for (var key in options.headers) { |
| 306 |
var value = options.headers[key]; |
| 307 |
if (goog.isDefAndNotNull(value)) { |
| 308 |
request.setRequestHeader(key, value); |
| 309 |
} |
| 310 |
} |
| 311 |
contentType = options.headers[xhr.CONTENT_TYPE_HEADER]; |
| 312 |
} |
| 313 |
|
| 314 |
// Browsers will automatically set the content type to multipart/form-data |
| 315 |
// when passed a FormData object. |
| 316 |
var dataIsFormData = |
| 317 |
(goog.global['FormData'] && (data instanceof goog.global['FormData'])); |
| 318 |
// If a content type hasn't been set, it hasn't been explicitly set to null, |
| 319 |
// and the data isn't a FormData, default to form-urlencoded/UTF8 for POSTs. |
| 320 |
// This is because some proxies have been known to reject posts without a |
| 321 |
// content-type. |
| 322 |
if (method == 'POST' && contentType === undefined && !dataIsFormData) { |
| 323 |
request.setRequestHeader(xhr.CONTENT_TYPE_HEADER, xhr.FORM_CONTENT_TYPE); |
| 324 |
} |
| 325 |
|
| 326 |
// Set whether to include cookies with cross-domain requests. See: |
| 327 |
// http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute |
| 328 |
if (options.withCredentials) { |
| 329 |
request.withCredentials = options.withCredentials; |
| 330 |
} |
| 331 |
|
| 332 |
// Allows setting an alternative response type, such as an ArrayBuffer. See: |
| 333 |
// http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-responsetype |
| 334 |
if (options.responseType) { |
| 335 |
request.responseType = options.responseType; |
| 336 |
} |
| 337 |
|
| 338 |
// Allow the request to override the MIME type of the response. See: |
| 339 |
// http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-overridemimetype |
| 340 |
if (options.mimeType) { |
| 341 |
request.overrideMimeType(options.mimeType); |
| 342 |
} |
| 343 |
|
| 344 |
// Handle timeouts, if requested. |
| 345 |
if (options.timeoutMs > 0) { |
| 346 |
timer = goog.global.setTimeout(function() { |
| 347 |
// Clear event listener before aborting so the errback will not be |
| 348 |
// called twice. |
| 349 |
request.onreadystatechange = goog.nullFunction; |
| 350 |
request.abort(); |
| 351 |
reject(new xhr.TimeoutError(url, request)); |
| 352 |
}, options.timeoutMs); |
| 353 |
} |
| 354 |
|
| 355 |
// Trigger the send. |
| 356 |
try { |
| 357 |
request.send(data); |
| 358 |
} catch (e) { |
| 359 |
// XMLHttpRequest.send is known to throw on some versions of FF, |
| 360 |
// for example if a cross-origin request is disallowed. |
| 361 |
request.onreadystatechange = goog.nullFunction; |
| 362 |
goog.global.clearTimeout(timer); |
| 363 |
reject(new xhr.Error('Error sending XHR: ' + e.message, url, request)); |
| 364 |
} |
| 365 |
}); |
| 366 |
return result.thenCatch(function(error) { |
| 367 |
if (error instanceof goog.Promise.CancellationError) { |
| 368 |
request.abort(); |
| 369 |
} |
| 370 |
throw error; |
| 371 |
}); |
| 372 |
}; |
| 373 |
|
| 374 |
|
| 375 |
/** |
| 376 |
* @param {string} url The URL to test. |
| 377 |
* @return {boolean} Whether the effective scheme is HTTP or HTTPs. |
| 378 |
* @private |
| 379 |
*/ |
| 380 |
xhr.isEffectiveSchemeHttp_ = function(url) { |
| 381 |
var scheme = goog.uri.utils.getEffectiveScheme(url); |
| 382 |
// NOTE(user): Empty-string is for the case under FF3.5 when the location |
| 383 |
// is not defined inside a web worker. |
| 384 |
return scheme == 'http' || scheme == 'https' || scheme == ''; |
| 385 |
}; |
| 386 |
|
| 387 |
|
| 388 |
/** |
| 389 |
* JSON-parses the given response text, returning an Object. |
| 390 |
* |
| 391 |
* @param {string} responseText Response text. |
| 392 |
* @param {xhr.Options|undefined} options The options object. |
| 393 |
* @return {Object} The JSON-parsed value of the original responseText. |
| 394 |
* @private |
| 395 |
*/ |
| 396 |
xhr.parseJson_ = function(responseText, options) { |
| 397 |
var prefixStrippedResult = responseText; |
| 398 |
if (options && options.xssiPrefix) { |
| 399 |
prefixStrippedResult = |
| 400 |
xhr.stripXssiPrefix_(options.xssiPrefix, prefixStrippedResult); |
| 401 |
} |
| 402 |
return /** @type {!Object} */ (JSON.parse(prefixStrippedResult)); |
| 403 |
}; |
| 404 |
|
| 405 |
|
| 406 |
/** |
| 407 |
* Strips the XSSI prefix from the input string. |
| 408 |
* |
| 409 |
* @param {string} prefix The XSSI prefix. |
| 410 |
* @param {string} string The string to strip the prefix from. |
| 411 |
* @return {string} The input string without the prefix. |
| 412 |
* @private |
| 413 |
*/ |
| 414 |
xhr.stripXssiPrefix_ = function(prefix, string) { |
| 415 |
if (goog.string.startsWith(string, prefix)) { |
| 416 |
string = string.substring(prefix.length); |
| 417 |
} |
| 418 |
return string; |
| 419 |
}; |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
/** |
| 424 |
* Generic error that may occur during a request. |
| 425 |
* |
| 426 |
* @param {string} message The error message. |
| 427 |
* @param {string} url The URL that was being requested. |
| 428 |
* @param {!goog.net.XhrLike.OrNative} request The XHR that failed. |
| 429 |
* @extends {goog.debug.Error} |
| 430 |
* @constructor |
| 431 |
*/ |
| 432 |
xhr.Error = function(message, url, request) { |
| 433 |
xhr.Error.base(this, 'constructor', message + ', url=' + url); |
| 434 |
|
| 435 |
/** |
| 436 |
* The URL that was requested. |
| 437 |
* @type {string} |
| 438 |
*/ |
| 439 |
this.url = url; |
| 440 |
|
| 441 |
/** |
| 442 |
* The XMLHttpRequest corresponding with the failed request. |
| 443 |
* @type {!goog.net.XhrLike.OrNative} |
| 444 |
*/ |
| 445 |
this.xhr = request; |
| 446 |
}; |
| 447 |
goog.inherits(xhr.Error, goog.debug.Error); |
| 448 |
|
| 449 |
|
| 450 |
/** @override */ |
| 451 |
xhr.Error.prototype.name = 'XhrError'; |
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
/** |
| 456 |
* Class for HTTP errors. |
| 457 |
* |
| 458 |
* @param {number} status The HTTP status code of the response. |
| 459 |
* @param {string} url The URL that was being requested. |
| 460 |
* @param {!goog.net.XhrLike.OrNative} request The XHR that failed. |
| 461 |
* @extends {xhr.Error} |
| 462 |
* @constructor |
| 463 |
* @final |
| 464 |
*/ |
| 465 |
xhr.HttpError = function(status, url, request) { |
| 466 |
xhr.HttpError.base( |
| 467 |
this, 'constructor', 'Request Failed, status=' + status, url, request); |
| 468 |
|
| 469 |
/** |
| 470 |
* The HTTP status code for the error. |
| 471 |
* @type {number} |
| 472 |
*/ |
| 473 |
this.status = status; |
| 474 |
}; |
| 475 |
goog.inherits(xhr.HttpError, xhr.Error); |
| 476 |
|
| 477 |
|
| 478 |
/** @override */ |
| 479 |
xhr.HttpError.prototype.name = 'XhrHttpError'; |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
/** |
| 484 |
* Class for Timeout errors. |
| 485 |
* |
| 486 |
* @param {string} url The URL that timed out. |
| 487 |
* @param {!goog.net.XhrLike.OrNative} request The XHR that failed. |
| 488 |
* @extends {xhr.Error} |
| 489 |
* @constructor |
| 490 |
* @final |
| 491 |
*/ |
| 492 |
xhr.TimeoutError = function(url, request) { |
| 493 |
xhr.TimeoutError.base(this, 'constructor', 'Request timed out', url, request); |
| 494 |
}; |
| 495 |
goog.inherits(xhr.TimeoutError, xhr.Error); |
| 496 |
|
| 497 |
|
| 498 |
/** @override */ |
| 499 |
xhr.TimeoutError.prototype.name = 'XhrTimeoutError'; |
| 500 |
|
| 501 |
}); // goog.scope |