parseHeaders.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // Header names are data, including __proto__; avoid inherited setters.
  40. const parsed = Object.create(null);
  41. let key;
  42. let val;
  43. let i;
  44. rawHeaders &&
  45. rawHeaders.split('\n').forEach(function parser(line) {
  46. i = line.indexOf(':');
  47. key = line.substring(0, i).trim().toLowerCase();
  48. val = line.substring(i + 1).trim();
  49. const hasKey = utils.hasOwnProp(parsed, key);
  50. if (!key || (hasKey && utils.hasOwnProp(ignoreDuplicateOf, key))) {
  51. return;
  52. }
  53. if (key === 'set-cookie') {
  54. if (hasKey) {
  55. parsed[key].push(val);
  56. } else {
  57. parsed[key] = [val];
  58. }
  59. } else {
  60. parsed[key] = hasKey ? parsed[key] + ', ' + val : val;
  61. }
  62. });
  63. return parsed;
  64. };