- Spec files
npm-axios
Describes: pkg:npm/axios@1.11.x
- Description
- Promise based HTTP client for the browser and node.js
- Author
- tessl
- Last updated
headers.md docs/
1# Headers Management23Advanced header manipulation with type-safe operations, automatic content-type handling, and specialized methods for common HTTP headers.45## Capabilities67### AxiosHeaders Class89Powerful header management class with advanced manipulation methods and type safety.1011```javascript { .api }12/**13* Advanced headers management class14*/15class AxiosHeaders {16constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);1718/** Allow bracket notation access */19[key: string]: any;2021/** Set header value with optional rewrite control */22set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;23set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;2425/** Get header value with optional parsing */26get(headerName: string, parser: RegExp): RegExpExecArray | null;27get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;2829/** Check if header exists */30has(header: string, matcher?: AxiosHeaderMatcher): boolean;3132/** Delete header(s) */33delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;3435/** Clear headers matching criteria */36clear(matcher?: AxiosHeaderMatcher): boolean;3738/** Normalize header names */39normalize(format: boolean): AxiosHeaders;4041/** Concatenate with other headers */42concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;4344/** Convert to plain object */45toJSON(asStrings?: boolean): RawAxiosHeaders;46}4748type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;49type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);50type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;51```5253**Usage Examples:**5455```javascript56import { AxiosHeaders } from "axios";5758// Create headers from object59const headers = new AxiosHeaders({60"Content-Type": "application/json",61"Authorization": "Bearer token123"62});6364// Set individual headers65headers.set("X-Custom-Header", "custom-value");66headers.set("Accept", "application/json");6768// Set multiple headers at once69headers.set({70"User-Agent": "MyApp/1.0",71"X-API-Version": "v2"72});7374// Get header values75const contentType = headers.get("Content-Type");76const auth = headers.get("authorization"); // Case-insensitive7778// Check if header exists79if (headers.has("Authorization")) {80console.log("Auth header is present");81}8283// Delete headers84headers.delete("X-Temporary-Header");8586// Convert to plain object87const plainHeaders = headers.toJSON();88console.log(plainHeaders);89```9091### Static Methods9293Factory and utility methods for header creation and manipulation.9495```javascript { .api }96/**97* Create AxiosHeaders from various sources98* @param thing - Source to create headers from99* @returns New AxiosHeaders instance100*/101static AxiosHeaders.from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;102103/**104* Create header accessor for specific header105* @param header - Header name or names106* @returns AxiosHeaders with accessor methods107*/108static AxiosHeaders.accessor(header: string | string[]): AxiosHeaders;109110/**111* Concatenate multiple header sources112* @param targets - Header sources to concatenate113* @returns New AxiosHeaders with combined headers114*/115static AxiosHeaders.concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;116```117118**Usage Examples:**119120```javascript121// Create from different sources122const fromObject = AxiosHeaders.from({123"Content-Type": "application/json"124});125126const fromString = AxiosHeaders.from("Content-Type: application/json\r\nAuthorization: Bearer token");127128const fromExisting = AxiosHeaders.from(existingHeaders);129130// Create accessor131const contentTypeAccessor = AxiosHeaders.accessor("Content-Type");132133// Concatenate headers134const combined = AxiosHeaders.concat(135{ "Accept": "application/json" },136new AxiosHeaders({ "Authorization": "Bearer token" }),137"X-Custom: value"138);139```140141### Specialized Header Methods142143Type-safe methods for common HTTP headers with automatic parsing and validation.144145```javascript { .api }146// Content-Type management147setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;148getContentType(parser?: RegExp): RegExpExecArray | null;149getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;150hasContentType(matcher?: AxiosHeaderMatcher): boolean;151152// Content-Length management153setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;154getContentLength(parser?: RegExp): RegExpExecArray | null;155getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;156hasContentLength(matcher?: AxiosHeaderMatcher): boolean;157158// Accept header management159setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;160getAccept(parser?: RegExp): RegExpExecArray | null;161getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;162hasAccept(matcher?: AxiosHeaderMatcher): boolean;163164// User-Agent management165setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;166getUserAgent(parser?: RegExp): RegExpExecArray | null;167getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;168hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;169170// Content-Encoding management171setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;172getContentEncoding(parser?: RegExp): RegExpExecArray | null;173getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;174hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;175176// Authorization management177setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;178getAuthorization(parser?: RegExp): RegExpExecArray | null;179getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;180hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;181182// Set-Cookie handling183getSetCookie(): string[];184185type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data'186| 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';187```188189**Usage Examples:**190191```javascript192const headers = new AxiosHeaders();193194// Content-Type management195headers.setContentType("application/json");196headers.setContentType("multipart/form-data", true); // Force rewrite197198const contentType = headers.getContentType();199console.log(contentType); // "multipart/form-data"200201if (headers.hasContentType(/^application\//)) {202console.log("Application content type");203}204205// Authorization management206headers.setAuthorization("Bearer eyJhbGciOiJIUzI1NiIs...");207const authToken = headers.getAuthorization(/Bearer (.+)/);208console.log(authToken); // ["Bearer eyJhbGc...", "eyJhbGc..."]209210// Accept header211headers.setAccept("application/json, text/plain, */*");212213// User-Agent214headers.setUserAgent("MyApp/1.0 (Platform/Version)");215216// Content-Length (usually set automatically)217headers.setContentLength(1024);218219// Set-Cookie handling (typically in responses)220const cookies = headers.getSetCookie(); // Returns array of cookie strings221```222223### Header Iteration224225Iterate over headers using standard iteration methods.226227```javascript { .api }228/**229* Iterator for header name-value pairs230*/231[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;232```233234**Usage Examples:**235236```javascript237const headers = new AxiosHeaders({238"Content-Type": "application/json",239"Authorization": "Bearer token",240"Accept": "application/json"241});242243// Iterate over all headers244for (const [name, value] of headers) {245console.log(`${name}: ${value}`);246}247248// Convert to array249const headerEntries = Array.from(headers);250251// Use with destructuring252const headerMap = new Map(headers);253```254255### Request and Response Header Types256257Type definitions for request and response headers.258259```javascript { .api }260// Request headers261interface RawAxiosRequestHeaders extends Partial<RawAxiosHeaders & {262'Accept': AxiosHeaderValue;263'Content-Length': AxiosHeaderValue;264'User-Agent': AxiosHeaderValue;265'Content-Encoding': AxiosHeaderValue;266'Authorization': AxiosHeaderValue;267'Content-Type': ContentType;268}> {}269270type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;271272// Response headers273interface RawAxiosResponseHeaders extends Partial<RawAxiosHeaders & {274'Server': AxiosHeaderValue;275'Content-Type': AxiosHeaderValue;276'Content-Length': AxiosHeaderValue;277'Cache-Control': AxiosHeaderValue;278'Content-Encoding': AxiosHeaderValue;279'set-cookie': string[];280}> {}281282type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;283284// Method-specific headers285type MethodsHeaders = Partial<{286[Key in Method as Lowercase<Key>]: AxiosHeaders;287} & {common: AxiosHeaders}>;288```289290### Default Headers Configuration291292Configure default headers for different HTTP methods.293294```javascript { .api }295interface HeadersDefaults {296common: RawAxiosRequestHeaders;297delete: RawAxiosRequestHeaders;298get: RawAxiosRequestHeaders;299head: RawAxiosRequestHeaders;300post: RawAxiosRequestHeaders;301put: RawAxiosRequestHeaders;302patch: RawAxiosRequestHeaders;303options?: RawAxiosRequestHeaders;304purge?: RawAxiosRequestHeaders;305link?: RawAxiosRequestHeaders;306unlink?: RawAxiosRequestHeaders;307}308```309310**Usage Examples:**311312```javascript313import axios from "axios";314315// Set common headers for all requests316axios.defaults.headers.common["Authorization"] = "Bearer token123";317axios.defaults.headers.common["X-API-Version"] = "v2";318319// Set method-specific headers320axios.defaults.headers.post["Content-Type"] = "application/json";321axios.defaults.headers.get["Accept"] = "application/json";322323// Instance-specific headers324const apiClient = axios.create();325apiClient.defaults.headers.common["User-Agent"] = "MyApp/1.0";326apiClient.defaults.headers.post["Content-Type"] = "application/json";327328// Headers in request config329const response = await axios.get("/api/users", {330headers: {331"Accept": "application/json",332"X-Request-ID": generateRequestId()333}334});335336// Using AxiosHeaders in config337const customHeaders = new AxiosHeaders()338.setAuthorization("Bearer token")339.setContentType("application/json")340.set("X-Custom", "value");341342const postResponse = await axios.post("/api/data", payload, {343headers: customHeaders344});345```346347### Header Matching and Filtering348349Advanced header matching with custom matchers.350351**Usage Examples:**352353```javascript354const headers = new AxiosHeaders({355"Content-Type": "application/json",356"X-Custom-Header": "custom-value",357"Authorization": "Bearer token123",358"Accept": "application/json, text/plain"359});360361// String matcher (case-insensitive)362const hasAuth = headers.has("authorization");363364// RegExp matcher365const hasJsonContent = headers.has("Content-Type", /application\/json/);366367// Function matcher368const hasCustomHeaders = headers.has("", (value, name) => {369return name.toLowerCase().startsWith("x-");370});371372// Delete headers matching pattern373headers.delete("", /^x-/i); // Delete all X- headers374375// Clear headers with custom matcher376headers.clear((value, name) => {377return name.toLowerCase().includes("temp");378});379380// Conditional header setting381const rewriteIfEmpty = (value, name) => !value || value.length === 0;382headers.set("Accept", "application/json", rewriteIfEmpty);383```384385### Advanced Header Patterns386387Complex header management patterns for real-world applications.388389**Usage Examples:**390391```javascript392// Header builder pattern393class HeaderBuilder {394constructor() {395this.headers = new AxiosHeaders();396}397398auth(token) {399this.headers.setAuthorization(`Bearer ${token}`);400return this;401}402403json() {404this.headers.setContentType("application/json");405this.headers.setAccept("application/json");406return this;407}408409userAgent(ua) {410this.headers.setUserAgent(ua);411return this;412}413414custom(name, value) {415this.headers.set(name, value);416return this;417}418419build() {420return this.headers;421}422}423424// Usage425const headers = new HeaderBuilder()426.auth("token123")427.json()428.userAgent("MyApp/1.0")429.custom("X-Request-ID", generateId())430.build();431432// Conditional headers433function buildHeaders(options = {}) {434const headers = new AxiosHeaders();435436if (options.auth) {437headers.setAuthorization(`Bearer ${options.auth}`);438}439440if (options.contentType) {441headers.setContentType(options.contentType);442} else {443headers.setContentType("application/json");444}445446if (options.accept) {447headers.setAccept(options.accept);448}449450if (options.custom) {451Object.entries(options.custom).forEach(([name, value]) => {452headers.set(name, value);453});454}455456return headers;457}458459// Header merging strategy460function mergeHeaders(base, override) {461const result = AxiosHeaders.from(base);462463if (override) {464return result.concat(override);465}466467return result;468}469470// Dynamic headers based on environment471function getEnvironmentHeaders() {472const headers = new AxiosHeaders();473474if (process.env.NODE_ENV === "development") {475headers.set("X-Debug", "true");476}477478if (process.env.API_VERSION) {479headers.set("X-API-Version", process.env.API_VERSION);480}481482return headers;483}484```