Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Last active August 29, 2015 14:15
Show Gist options
  • Save nijikokun/3f210c20cbccd3d21687 to your computer and use it in GitHub Desktop.
Save nijikokun/3f210c20cbccd3d21687 to your computer and use it in GitHub Desktop.
Extend XMLHttpRequest to get a key-value object by parsing getAllResponseHeaders
/**
* Parses XMLHttpRequest getAllResponseHeaders into a key-value map
*/
function getResponseHeaderObject (xhrObject) {
var headers = xhrObject.getAllResponseHeaders()
var list = {}
var pairs
if (!headers) {
return list
}
pairs = headers.split('\u000d\u000a')
for (var i = 0, length = pairs.length; i < length; i++) {
var pair = pairs[i]
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
var index = pair.indexOf('\u003a\u0020')
if (index > 0) {
var key = pair.substring(0, index)
var val = pair.substring(index + 2)
list[key] = val
}
}
return list
}
@ahmadnassri
Copy link

remove line 5 and it can be used in node, and for both request / response headers too... just pass in headers string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment