Bring some sanity to request parsing and error handling (#2335)

* Update docs/request.md
* Bring some sanity to request parsing and error handling

- The browser can do JSON parsing itself. Let's defer to that where
  possible. (A few IE hacks are required here, though.)
- Don't propagate any error that occurs before `deserialize`/`extract`.
- Allow sending raw array buffers/blobs/etc. to `deserialize`.
- Align behavior more closely with the XHR spec.
- Send the more useful parsed response to `deserialize`, not the less
  useful string response.
This commit is contained in:
Isiah Meadows 2019-05-29 09:41:22 -04:00 committed by GitHub
parent 09afc54c7b
commit 794e8e963f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 55 additions and 18 deletions

View file

@ -43,13 +43,28 @@ module.exports = function() {
args.user = user
args.password = password
}
this.responseType = ""
this.response = null
Object.defineProperty(this, "responseText", {get: function() {
if (this.responseType === "" || this.responseType === "text") {
return this.response
} else {
throw new Error("Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was '" + this.responseType + "').")
}
}})
this.send = function(body) {
var self = this
if(!aborted) {
var handler = routes[args.method + " " + args.pathname] || serverErrorHandler.bind(null, args.pathname)
var data = handler({url: args.pathname, query: args.search || {}, body: body || null})
self.status = data.status
self.responseText = data.responseText
// Match spec
if (self.responseType === "json") {
try { self.response = JSON.parse(data.responseText) }
catch (e) { /* ignore */ }
} else {
self.response = data.responseText
}
} else {
self.status = 0
}