parseResponseHeaders.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  3. * a dictionary.
  4. *
  5. * @function parseResponseHeaders
  6. *
  7. * @param {string} headerString The header string returned by getAllResponseHeaders(). The format is
  8. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  9. * @returns {object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  10. * is that header's value.
  11. *
  12. * @private
  13. */
  14. function parseResponseHeaders(headerString) {
  15. const headers = {};
  16. if (!headerString) {
  17. return headers;
  18. }
  19. const headerPairs = headerString.split("\u000d\u000a");
  20. for (let i = 0; i < headerPairs.length; ++i) {
  21. const headerPair = headerPairs[i];
  22. // Can't use split() here because it does the wrong thing
  23. // if the header value has the string ": " in it.
  24. const index = headerPair.indexOf("\u003a\u0020");
  25. if (index > 0) {
  26. const key = headerPair.substring(0, index);
  27. const val = headerPair.substring(index + 2);
  28. headers[key] = val;
  29. }
  30. }
  31. return headers;
  32. }
  33. export default parseResponseHeaders;