parseHeaders.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. import utils from '../utils.js';
  3. // RawAxiosHeaders whose duplicates are ignored by node
  4. // c.f. https://nodejs.org/api/http.html#http_message_headers
  5. const ignoreDuplicateOf = utils.toObjectSet([
  6. 'age',
  7. 'authorization',
  8. 'content-length',
  9. 'content-type',
  10. 'etag',
  11. 'expires',
  12. 'from',
  13. 'host',
  14. 'if-modified-since',
  15. 'if-unmodified-since',
  16. 'last-modified',
  17. 'location',
  18. 'max-forwards',
  19. 'proxy-authorization',
  20. 'referer',
  21. 'retry-after',
  22. 'user-agent',
  23. ]);
  24. /**
  25. * Parse headers into an object
  26. *
  27. * ```
  28. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  29. * Content-Type: application/json
  30. * Connection: keep-alive
  31. * Transfer-Encoding: chunked
  32. * ```
  33. *
  34. * @param {String} rawHeaders Headers needing to be parsed
  35. *
  36. * @returns {Object} Headers parsed into an object
  37. */
  38. export default (rawHeaders) => {
  39. const parsed = {};
  40. let key;
  41. let val;
  42. let i;
  43. rawHeaders &&
  44. rawHeaders.split('\n').forEach(function parser(line) {
  45. i = line.indexOf(':');
  46. key = line.substring(0, i).trim().toLowerCase();
  47. val = line.substring(i + 1).trim();
  48. const hasKey = utils.hasOwnProp(parsed, key);
  49. if (!key || (hasKey && utils.hasOwnProp(ignoreDuplicateOf, key))) {
  50. return;
  51. }
  52. if (key === 'set-cookie') {
  53. if (hasKey) {
  54. parsed[key].push(val);
  55. } else {
  56. parsed[key] = [val];
  57. }
  58. } else {
  59. parsed[key] = hasKey ? parsed[key] + ', ' + val : val;
  60. }
  61. });
  62. return parsed;
  63. };