- Spec files
npm-axios
Describes: pkg:npm/axios@1.6.x
- Description
- Promise based HTTP client for the browser and node.js
- Author
- tessl
- Last updated
headers-management.md docs/
1# Headers Management23Sophisticated HTTP headers management with the AxiosHeaders class providing type-safe header operations, automatic normalization, and convenient methods for common headers.45## Capabilities67### AxiosHeaders Class89Comprehensive HTTP headers management class with type-safe operations.1011```typescript { .api }12class AxiosHeaders {13/**14* Creates new AxiosHeaders instance15* @param headers - Initial headers (object, string, or AxiosHeaders)16*/17constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);1819/** Index signature for dynamic header access */20[key: string]: any;2122/**23* Set header value(s)24* @param headerName - Header name25* @param value - Header value26* @param rewrite - Whether to overwrite existing header27* @returns AxiosHeaders instance for chaining28*/29set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;30set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;3132/**33* Get header value34* @param headerName - Header name35* @param parser - RegExp for parsing header value36* @returns Parsed header value or null37*/38get(headerName: string, parser: RegExp): RegExpExecArray | null;39get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;4041/**42* Check if header exists43* @param header - Header name44* @param matcher - Optional matcher function45* @returns Whether header exists46*/47has(header: string, matcher?: AxiosHeaderMatcher): boolean;4849/**50* Delete header(s)51* @param header - Header name(s) to delete52* @param matcher - Optional matcher function53* @returns Whether any headers were deleted54*/55delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;5657/**58* Clear headers matching criteria59* @param matcher - Optional matcher function60* @returns Whether any headers were cleared61*/62clear(matcher?: AxiosHeaderMatcher): boolean;6364/**65* Normalize header names66* @param format - Whether to format header names67* @returns AxiosHeaders instance68*/69normalize(format: boolean): AxiosHeaders;7071/**72* Concatenate with other headers73* @param targets - Headers to concatenate74* @returns New AxiosHeaders instance75*/76concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;7778/**79* Convert to plain object80* @param asStrings - Whether to convert all values to strings81* @returns Plain object representation82*/83toJSON(asStrings?: boolean): RawAxiosHeaders;8485/**86* Create AxiosHeaders from various inputs87* @param thing - Input to convert88* @returns New AxiosHeaders instance89*/90static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;9192/**93* Create header accessor94* @param header - Header name(s)95* @returns AxiosHeaders instance96*/97static accessor(header: string | string[]): AxiosHeaders;9899/**100* Concatenate multiple header sources101* @param targets - Headers to concatenate102* @returns New AxiosHeaders instance103*/104static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;105106/** Iterator for header entries */107[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;108}109110type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;111112type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);113114type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;115116interface RawAxiosHeaders {117[key: string]: AxiosHeaderValue;118}119```120121**Usage Examples:**122123```typescript124import { AxiosHeaders } from "axios";125126// Create headers from object127const headers = new AxiosHeaders({128"Content-Type": "application/json",129"Authorization": "Bearer token123",130"X-Custom-Header": "value"131});132133// Create from string (HTTP header format)134const headersFromString = new AxiosHeaders(`135Content-Type: application/json136Authorization: Bearer token123137X-Custom-Header: value138`);139140// Set individual headers141headers.set("User-Agent", "MyApp/1.0.0");142headers.set("Accept", "application/json, text/plain");143144// Set multiple headers at once145headers.set({146"Cache-Control": "no-cache",147"X-Requested-With": "XMLHttpRequest"148});149150// Get header values151console.log(headers.get("Content-Type")); // "application/json"152console.log(headers.get("authorization")); // "Bearer token123" (case-insensitive)153154// Check if header exists155console.log(headers.has("Content-Type")); // true156console.log(headers.has("X-Nonexistent")); // false157158// Delete headers159headers.delete("X-Custom-Header");160headers.delete(["Cache-Control", "X-Requested-With"]);161162// Convert to plain object163const plainHeaders = headers.toJSON();164console.log(plainHeaders);165```166167### Common Header Methods168169Convenient methods for working with standard HTTP headers.170171```typescript { .api }172// Content-Type methods173setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;174getContentType(parser?: RegExp): RegExpExecArray | null;175getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;176hasContentType(matcher?: AxiosHeaderMatcher): boolean;177178// Content-Length methods179setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;180getContentLength(parser?: RegExp): RegExpExecArray | null;181getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;182hasContentLength(matcher?: AxiosHeaderMatcher): boolean;183184// Accept methods185setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;186getAccept(parser?: RegExp): RegExpExecArray | null;187getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;188hasAccept(matcher?: AxiosHeaderMatcher): boolean;189190// User-Agent methods191setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;192getUserAgent(parser?: RegExp): RegExpExecArray | null;193getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;194hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;195196// Content-Encoding methods197setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;198getContentEncoding(parser?: RegExp): RegExpExecArray | null;199getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;200hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;201202// Authorization methods203setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;204getAuthorization(parser?: RegExp): RegExpExecArray | null;205getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;206hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;207208type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';209```210211**Usage Examples:**212213```typescript214import { AxiosHeaders } from "axios";215216const headers = new AxiosHeaders();217218// Content-Type methods219headers.setContentType("application/json");220console.log(headers.getContentType()); // "application/json"221console.log(headers.hasContentType()); // true222223// Authorization methods224headers.setAuthorization("Bearer token123");225console.log(headers.getAuthorization()); // "Bearer token123"226227// User-Agent methods228headers.setUserAgent("MyApp/1.0.0 (Windows NT 10.0)");229console.log(headers.getUserAgent()); // "MyApp/1.0.0 (Windows NT 10.0)"230231// Accept methods232headers.setAccept("application/json, text/plain, */*");233console.log(headers.getAccept()); // "application/json, text/plain, */*"234235// Content-Encoding methods236headers.setContentEncoding("gzip");237console.log(headers.getContentEncoding()); // "gzip"238239// Content-Length methods240headers.setContentLength("1024");241console.log(headers.getContentLength()); // "1024"242243// Parse header values with RegExp244const authValue = headers.getAuthorization(/Bearer (.+)/);245if (authValue) {246console.log("Token:", authValue[1]); // "token123"247}248```249250### Header Concatenation and Merging251252Combine headers from multiple sources with proper handling of duplicates.253254**Usage Examples:**255256```typescript257import { AxiosHeaders } from "axios";258259// Create base headers260const baseHeaders = new AxiosHeaders({261"User-Agent": "MyApp/1.0.0",262"Accept": "application/json"263});264265// Create additional headers266const authHeaders = new AxiosHeaders({267"Authorization": "Bearer token123",268"X-Client-Version": "1.0.0"269});270271// Concatenate headers272const combinedHeaders = baseHeaders.concat(authHeaders, {273"Content-Type": "application/json",274"X-Request-ID": "req-123"275});276277console.log(combinedHeaders.toJSON());278// {279// "User-Agent": "MyApp/1.0.0",280// "Accept": "application/json",281// "Authorization": "Bearer token123",282// "X-Client-Version": "1.0.0",283// "Content-Type": "application/json",284// "X-Request-ID": "req-123"285// }286287// Static concatenation288const mergedHeaders = AxiosHeaders.concat(289{ "Accept": "application/json" },290{ "Content-Type": "application/json" },291"Authorization: Bearer token\nX-Custom: value"292);293294// Create from various sources295const headers1 = AxiosHeaders.from({ "Content-Type": "application/json" });296const headers2 = AxiosHeaders.from("Authorization: Bearer token");297const headers3 = AxiosHeaders.from(headers1);298```299300### Header Iteration and Processing301302Iterate through headers and process them programmatically.303304**Usage Examples:**305306```typescript307import { AxiosHeaders } from "axios";308309const headers = new AxiosHeaders({310"Content-Type": "application/json",311"Authorization": "Bearer token123",312"X-Custom-Header": "value",313"Accept": "application/json"314});315316// Iterate through headers317for (const [name, value] of headers) {318console.log(`${name}: ${value}`);319}320321// Convert to array of entries322const entries = Array.from(headers);323console.log(entries);324// [325// ["Content-Type", "application/json"],326// ["Authorization", "Bearer token123"],327// ["X-Custom-Header", "value"],328// ["Accept", "application/json"]329// ]330331// Filter headers332const customHeaders = new AxiosHeaders();333for (const [name, value] of headers) {334if (name.startsWith("X-")) {335customHeaders.set(name, value);336}337}338339// Process headers with Array methods340const headerNames = Array.from(headers).map(([name]) => name);341console.log("Header names:", headerNames);342343const hasAuthHeader = Array.from(headers).some(([name]) =>344name.toLowerCase() === "authorization"345);346console.log("Has auth header:", hasAuthHeader);347```348349### Header Normalization and Formatting350351Normalize header names and values for consistency.352353**Usage Examples:**354355```typescript356import { AxiosHeaders } from "axios";357358// Headers with inconsistent casing359const headers = new AxiosHeaders({360"content-type": "application/json",361"AUTHORIZATION": "Bearer token123",362"X-custom-HEADER": "value"363});364365// Normalize headers (axios does this automatically)366const normalized = headers.normalize(true);367368console.log(normalized.toJSON());369// Headers are normalized to proper casing:370// {371// "Content-Type": "application/json",372// "Authorization": "Bearer token123",373// "X-Custom-Header": "value"374// }375376// Clear headers with matcher377headers.clear((value, name) => name.startsWith("X-"));378379// Delete headers with matcher380headers.delete("authorization", (value, name) =>381name.toLowerCase() === "authorization"382);383384// Set header with conditional rewrite385headers.set("Content-Type", "text/plain", (value, name) =>386value !== "application/json"387);388```389390### Request and Response Header Types391392Type definitions for request and response headers with common header names.393394```typescript { .api }395type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {396[Key in CommonRequestHeadersList]: AxiosHeaderValue;397} & {398'Content-Type': ContentType399}>;400401type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;402403type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;404405type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;406407type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization';408409type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control' | 'Content-Encoding';410411type RawCommonResponseHeaders = {412[Key in CommonResponseHeadersList]: AxiosHeaderValue;413} & {414"set-cookie": string[];415};416```417418**Usage Examples:**419420```typescript421import axios, { AxiosRequestHeaders, AxiosResponseHeaders } from "axios";422423// Typed request headers424const requestHeaders: AxiosRequestHeaders = new AxiosHeaders({425"Accept": "application/json",426"Content-Type": "application/json",427"Authorization": "Bearer token123",428"User-Agent": "MyApp/1.0.0"429});430431// Use in request432const response = await axios.post("https://api.example.com/data",433{ message: "Hello" },434{ headers: requestHeaders }435);436437// Access response headers438const responseHeaders: AxiosResponseHeaders = response.headers;439console.log(responseHeaders["content-type"]);440console.log(responseHeaders["cache-control"]);441console.log(responseHeaders["set-cookie"]); // Array of cookie strings442443// Type-safe header access444if (responseHeaders instanceof AxiosHeaders) {445console.log(responseHeaders.getContentType());446console.log(responseHeaders.getContentLength());447}448```