headers-polyfill.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. class Headers {
  2. constructor(init = {}) {
  3. this._headers = {};
  4. if (init instanceof Headers) {
  5. // 如果传入的是另一个 Headers 实例,复制其内容
  6. init.forEach((value, name) => {
  7. this.append(name, value);
  8. });
  9. } else if (init) {
  10. // 处理普通对象或数组
  11. Object.entries(init).forEach(([name, value]) => {
  12. if (Array.isArray(value)) {
  13. // 处理数组值(如 ['value1', 'value2'])
  14. value.forEach(v => this.append(name, v));
  15. } else {
  16. this.set(name, value);
  17. }
  18. });
  19. }
  20. }
  21. // 添加头(可重复添加同名头)
  22. append(name, value) {
  23. const normalizedName = this._normalizeName(name);
  24. if (this._headers[normalizedName]) {
  25. this._headers[normalizedName] += `, ${value}`;
  26. } else {
  27. this._headers[normalizedName] = String(value);
  28. }
  29. }
  30. // 设置头(覆盖同名头)
  31. set(name, value) {
  32. this._headers[this._normalizeName(name)] = String(value);
  33. }
  34. // 获取头
  35. get(name) {
  36. return this._headers[this._normalizeName(name)] || null;
  37. }
  38. // 检查是否存在头
  39. has(name) {
  40. return this._normalizeName(name) in this._headers;
  41. }
  42. // 删除头
  43. delete(name) {
  44. delete this._headers[this._normalizeName(name)];
  45. }
  46. // 遍历头
  47. forEach(callback) {
  48. Object.entries(this._headers).forEach(([name, value]) => {
  49. callback(value, name, this);
  50. });
  51. }
  52. // 获取所有头(原始对象)
  53. raw() {
  54. return { ...this._headers };
  55. }
  56. // 规范化头名称(转为小写)
  57. _normalizeName(name) {
  58. if (typeof name !== 'string') {
  59. throw new TypeError('Header name must be a string');
  60. }
  61. return name.toLowerCase();
  62. }
  63. }
  64. // 全局注册(如果需要)
  65. if (typeof globalThis.Headers === 'undefined') {
  66. globalThis.Headers = Headers;
  67. }
  68. export default Headers;