- 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
index.md docs/
1# Axios23Axios is a comprehensive promise-based HTTP client library designed for both browser and Node.js environments. It provides a clean, intuitive API for making HTTP requests with support for request and response interceptors, automatic JSON data transformation, client-side protection against XSRF, request and response timeout configuration, and comprehensive error handling.45## Package Information67- **Package Name**: axios8- **Package Type**: npm9- **Language**: JavaScript with TypeScript definitions10- **Installation**: `npm install axios`1112## Core Imports1314```typescript15import axios from "axios";16import { Axios, AxiosError, AxiosHeaders } from "axios";17```1819For CommonJS:2021```javascript22const axios = require("axios");23const { Axios, AxiosError, AxiosHeaders } = require("axios");24```2526## Basic Usage2728```typescript29import axios from "axios";3031// Simple GET request32const response = await axios.get("https://api.example.com/users");33console.log(response.data);3435// POST request with data36const newUser = await axios.post("https://api.example.com/users", {37name: "John Doe",38email: "john@example.com"39});4041// Request with configuration42const config = {43method: "get",44url: "https://api.example.com/users",45headers: {46"Authorization": "Bearer token"47},48timeout: 500049};50const response = await axios(config);51```5253## Architecture5455Axios is built around several key components:5657- **Main Instance**: Default configured axios instance with HTTP method shortcuts58- **Axios Class**: Core HTTP client class for creating custom instances59- **Interceptors**: Request/response middleware for automatic processing60- **Adapters**: Platform-specific implementations (XMLHttpRequest for browser, HTTP for Node.js)61- **Error Handling**: Comprehensive error system with detailed error information62- **Configuration**: Extensive configuration options for all aspects of HTTP requests63- **Headers Management**: Sophisticated header handling with the AxiosHeaders class64- **Cancellation**: Request cancellation support via AbortController and legacy CancelToken6566## Capabilities6768### HTTP Methods6970Core HTTP request methods with both functional and instance-based APIs. Supports all standard HTTP verbs with convenient method signatures.7172```typescript { .api }73// Default instance methods74function get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;75function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;76function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;77function patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;78function delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;79function head<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;80function options<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;8182// Generic request method83function request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>>;8485// Form-encoded requests86function postForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;87function putForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;88function patchForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;89```9091[HTTP Methods](./http-methods.md)9293### Instance Management9495Create and configure custom axios instances with their own defaults, interceptors, and configuration.9697```typescript { .api }98function create(config?: CreateAxiosDefaults): AxiosInstance;99100interface AxiosInstance extends Axios {101<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>>;102<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;103defaults: AxiosDefaults;104}105106class Axios {107constructor(config?: AxiosRequestConfig);108defaults: AxiosDefaults;109interceptors: {110request: AxiosInterceptorManager<InternalAxiosRequestConfig>;111response: AxiosInterceptorManager<AxiosResponse>;112};113}114```115116[Instance Management](./instance-management.md)117118### Request Configuration119120Comprehensive configuration system for customizing all aspects of HTTP requests including headers, timeouts, authentication, and more.121122```typescript { .api }123interface AxiosRequestConfig<D = any> {124url?: string;125method?: Method;126baseURL?: string;127transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];128transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];129headers?: RawAxiosRequestHeaders | AxiosHeaders;130params?: any;131data?: D;132timeout?: number;133withCredentials?: boolean;134auth?: AxiosBasicCredentials;135responseType?: ResponseType;136onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;137onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;138cancelToken?: CancelToken;139signal?: GenericAbortSignal;140}141142interface AxiosResponse<T = any> {143data: T;144status: number;145statusText: string;146headers: AxiosResponseHeaders;147config: InternalAxiosRequestConfig;148request?: any;149}150```151152[Request Configuration](./request-configuration.md)153154### Error Handling155156Comprehensive error handling system with detailed error information and type-safe error checking.157158```typescript { .api }159class AxiosError<T = unknown, D = any> extends Error {160constructor(161message?: string,162code?: string,163config?: InternalAxiosRequestConfig<D>,164request?: any,165response?: AxiosResponse<T, D>166);167168config?: InternalAxiosRequestConfig<D>;169code?: string;170request?: any;171response?: AxiosResponse<T, D>;172isAxiosError: boolean;173status?: number;174toJSON(): object;175176static from<T = unknown, D = any>(177error: Error | unknown,178code?: string,179config?: InternalAxiosRequestConfig<D>,180request?: any,181response?: AxiosResponse<T, D>,182customProps?: object183): AxiosError<T, D>;184}185186function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;187```188189[Error Handling](./error-handling.md)190191### Headers Management192193Sophisticated HTTP headers management with the AxiosHeaders class providing type-safe header operations.194195```typescript { .api }196class AxiosHeaders {197constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);198199set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;200get(headerName: string, matcher?: AxiosHeaderMatcher): AxiosHeaderValue;201has(header: string, matcher?: AxiosHeaderMatcher): boolean;202delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;203clear(matcher?: AxiosHeaderMatcher): boolean;204toJSON(asStrings?: boolean): RawAxiosHeaders;205206static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;207static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;208}209```210211[Headers Management](./headers-management.md)212213### Interceptors214215Request and response middleware system for automatic processing, authentication, logging, and error handling.216217```typescript { .api }218interface AxiosInterceptorManager<V> {219use(220onFulfilled?: ((value: V) => V | Promise<V>) | null,221onRejected?: ((error: any) => any) | null,222options?: AxiosInterceptorOptions223): number;224eject(id: number): void;225clear(): void;226}227228interface AxiosInterceptorOptions {229synchronous?: boolean;230runWhen?: (config: InternalAxiosRequestConfig) => boolean;231}232```233234[Interceptors](./interceptors.md)235236### Request Cancellation237238Request cancellation support using modern AbortController and legacy CancelToken for aborting in-flight requests.239240```typescript { .api }241// Modern cancellation with AbortController242interface GenericAbortSignal {243readonly aborted: boolean;244onabort?: ((...args: any) => any) | null;245addEventListener?: (...args: any) => any;246removeEventListener?: (...args: any) => any;247}248249// Legacy cancellation250class CancelToken {251constructor(executor: (cancel: Canceler) => void);252promise: Promise<Cancel>;253reason?: Cancel;254throwIfRequested(): void;255static source(): CancelTokenSource;256}257258class CanceledError<T> extends AxiosError<T> {}259260function isCancel(value: any): value is Cancel;261```262263[Request Cancellation](./request-cancellation.md)264265### Utility Functions266267Helper functions for common operations including data transformation, configuration merging, and adapter resolution.268269```typescript { .api }270function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;271function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;272function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;273function formToJSON(form: GenericFormData | GenericHTMLFormElement): object;274function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;275function mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;276```277278[Utility Functions](./utility-functions.md)279280## Types281282```typescript { .api }283type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';284285type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';286287type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;288289interface RawAxiosHeaders {290[key: string]: AxiosHeaderValue;291}292293interface AxiosBasicCredentials {294username: string;295password: string;296}297298interface AxiosProxyConfig {299host: string;300port: number;301auth?: AxiosBasicCredentials;302protocol?: string;303}304305interface AxiosProgressEvent {306loaded: number;307total?: number;308progress?: number;309bytes: number;310rate?: number;311estimated?: number;312upload?: boolean;313download?: boolean;314event?: any;315}316317enum HttpStatusCode {318Continue = 100,319SwitchingProtocols = 101,320Processing = 102,321EarlyHints = 103,322Ok = 200,323Created = 201,324Accepted = 202,325NonAuthoritativeInformation = 203,326NoContent = 204,327ResetContent = 205,328PartialContent = 206,329MultiStatus = 207,330AlreadyReported = 208,331ImUsed = 226,332MultipleChoices = 300,333MovedPermanently = 301,334Found = 302,335SeeOther = 303,336NotModified = 304,337UseProxy = 305,338Unused = 306,339TemporaryRedirect = 307,340PermanentRedirect = 308,341BadRequest = 400,342Unauthorized = 401,343PaymentRequired = 402,344Forbidden = 403,345NotFound = 404,346MethodNotAllowed = 405,347NotAcceptable = 406,348ProxyAuthenticationRequired = 407,349RequestTimeout = 408,350Conflict = 409,351Gone = 410,352LengthRequired = 411,353PreconditionFailed = 412,354PayloadTooLarge = 413,355UriTooLong = 414,356UnsupportedMediaType = 415,357RangeNotSatisfiable = 416,358ExpectationFailed = 417,359ImATeapot = 418,360MisdirectedRequest = 421,361UnprocessableEntity = 422,362Locked = 423,363FailedDependency = 424,364TooEarly = 425,365UpgradeRequired = 426,366PreconditionRequired = 428,367TooManyRequests = 429,368RequestHeaderFieldsTooLarge = 431,369UnavailableForLegalReasons = 451,370InternalServerError = 500,371NotImplemented = 501,372BadGateway = 502,373ServiceUnavailable = 503,374GatewayTimeout = 504,375HttpVersionNotSupported = 505,376VariantAlsoNegotiates = 506,377InsufficientStorage = 507,378LoopDetected = 508,379NotExtended = 510,380NetworkAuthenticationRequired = 511381}382```