- 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
request-configuration.md docs/
1# Request Configuration23Comprehensive configuration system for customizing all aspects of HTTP requests including URLs, headers, timeouts, authentication, data transformation, and more.45## Capabilities67### Request Configuration Interface89Complete configuration options for HTTP requests.1011```typescript { .api }12interface AxiosRequestConfig<D = any> {13/** Request URL */14url?: string;1516/** HTTP method */17method?: Method | string;1819/** Base URL for relative URLs */20baseURL?: string;2122/** Transform request data before sending */23transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];2425/** Transform response data after receiving */26transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];2728/** Request headers */29headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;3031/** URL parameters */32params?: any;3334/** Parameter serialization options */35paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;3637/** Request body data */38data?: D;3940/** Request timeout in milliseconds */41timeout?: number;4243/** Custom timeout error message */44timeoutErrorMessage?: string;4546/** Send credentials with cross-origin requests */47withCredentials?: boolean;4849/** Request adapter configuration */50adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];5152/** HTTP basic authentication */53auth?: AxiosBasicCredentials;5455/** Response data type */56responseType?: ResponseType;5758/** Response text encoding */59responseEncoding?: responseEncoding | string;6061/** XSRF cookie name */62xsrfCookieName?: string;6364/** XSRF header name */65xsrfHeaderName?: string;6667/** Upload progress callback */68onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;6970/** Download progress callback */71onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;7273/** Maximum response content length */74maxContentLength?: number;7576/** Status code validation function */77validateStatus?: ((status: number) => boolean) | null;7879/** Maximum request body length */80maxBodyLength?: number;8182/** Maximum redirects to follow */83maxRedirects?: number;8485/** Upload/download rate limiting */86maxRate?: number | [MaxUploadRate, MaxDownloadRate];8788/** Before redirect callback */89beforeRedirect?: (options: Record<string, any>, responseDetails: { headers: Record<string, string> }) => void;9091/** Unix socket path */92socketPath?: string | null;9394/** Custom transport */95transport?: any;9697/** HTTP agent for Node.js */98httpAgent?: any;99100/** HTTPS agent for Node.js */101httpsAgent?: any;102103/** Proxy configuration */104proxy?: AxiosProxyConfig | false;105106/** Legacy cancellation token */107cancelToken?: CancelToken;108109/** Decompress response */110decompress?: boolean;111112/** Transitional options */113transitional?: TransitionalOptions;114115/** Modern cancellation signal */116signal?: GenericAbortSignal;117118/** Use insecure HTTP parser */119insecureHTTPParser?: boolean;120121/** Environment configuration */122env?: {123FormData?: new (...args: any[]) => object;124};125126/** Form serialization options */127formSerializer?: FormSerializerOptions;128129/** IP address family */130family?: AddressFamily;131132/** DNS lookup function */133lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |134((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);135136/** XSRF token handling */137withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);138}139140type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';141142type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';143144type AddressFamily = 4 | 6 | undefined;145```146147**Usage Examples:**148149```typescript150import axios from "axios";151152// Complete configuration example153const config: AxiosRequestConfig = {154method: "post",155url: "https://api.example.com/users",156baseURL: "https://api.example.com",157headers: {158"Authorization": "Bearer token",159"Content-Type": "application/json",160"X-Custom-Header": "value"161},162data: {163name: "John Doe",164email: "john@example.com"165},166params: {167include: "profile,preferences"168},169timeout: 10000,170withCredentials: true,171responseType: "json",172validateStatus: (status) => status >= 200 && status < 300,173maxRedirects: 5,174onUploadProgress: (progressEvent) => {175const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);176console.log(`Upload ${percentCompleted}% completed`);177}178};179180const response = await axios(config);181```182183### Response Configuration184185Structure of HTTP response objects returned by axios.186187```typescript { .api }188interface AxiosResponse<T = any, D = any> {189/** Response data */190data: T;191192/** HTTP status code */193status: number;194195/** HTTP status text */196statusText: string;197198/** Response headers */199headers: RawAxiosResponseHeaders | AxiosResponseHeaders;200201/** Request configuration used */202config: InternalAxiosRequestConfig<D>;203204/** Request object (platform-specific) */205request?: any;206}207208type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;209210type RawCommonResponseHeaders = {211[Key in CommonResponseHeadersList]: AxiosHeaderValue;212} & {213"set-cookie": string[];214};215216type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control' | 'Content-Encoding';217```218219**Usage Examples:**220221```typescript222import axios from "axios";223224const response = await axios.get("https://api.example.com/users/123");225226// Access response properties227console.log(response.data); // Response body228console.log(response.status); // 200229console.log(response.statusText); // "OK"230console.log(response.headers["content-type"]); // "application/json"231console.log(response.config.url); // Original request URL232233// Typed response234interface User {235id: number;236name: string;237email: string;238}239240const response = await axios.get<User>("https://api.example.com/users/123");241console.log(response.data.name); // TypeScript knows this is a string242```243244### Authentication Configuration245246HTTP authentication options including basic auth and bearer tokens.247248```typescript { .api }249interface AxiosBasicCredentials {250username: string;251password: string;252}253```254255**Usage Examples:**256257```typescript258import axios from "axios";259260// Basic authentication261const response = await axios.get("https://api.example.com/secure", {262auth: {263username: "myuser",264password: "mypassword"265}266});267268// Bearer token in headers269const response = await axios.get("https://api.example.com/secure", {270headers: {271"Authorization": "Bearer your-jwt-token"272}273});274275// API key authentication276const response = await axios.get("https://api.example.com/data", {277headers: {278"X-API-Key": "your-api-key"279}280});281282// Custom authentication283const response = await axios.get("https://api.example.com/secure", {284headers: {285"Authorization": "Custom your-custom-token"286}287});288```289290### Proxy Configuration291292HTTP proxy settings for routing requests through proxy servers.293294```typescript { .api }295interface AxiosProxyConfig {296host: string;297port: number;298auth?: AxiosBasicCredentials;299protocol?: string;300}301```302303**Usage Examples:**304305```typescript306import axios from "axios";307308// HTTP proxy309const response = await axios.get("https://api.example.com/data", {310proxy: {311host: "proxy.company.com",312port: 8080313}314});315316// Proxy with authentication317const response = await axios.get("https://api.example.com/data", {318proxy: {319host: "proxy.company.com",320port: 8080,321auth: {322username: "proxyuser",323password: "proxypass"324}325}326});327328// HTTPS proxy329const response = await axios.get("https://api.example.com/data", {330proxy: {331protocol: "https",332host: "secure-proxy.company.com",333port: 8443334}335});336337// Disable proxy338const response = await axios.get("https://api.example.com/data", {339proxy: false340});341```342343### Progress Tracking344345Monitor upload and download progress with callback functions.346347```typescript { .api }348interface AxiosProgressEvent {349loaded: number;350total?: number;351progress?: number;352bytes: number;353rate?: number;354estimated?: number;355upload?: boolean;356download?: boolean;357event?: any;358}359```360361**Usage Examples:**362363```typescript364import axios from "axios";365366// Upload progress367const formData = new FormData();368formData.append("file", fileInput.files[0]);369370const response = await axios.post("https://api.example.com/upload", formData, {371onUploadProgress: (progressEvent) => {372if (progressEvent.total) {373const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);374console.log(`Upload ${percentCompleted}% completed`);375376// Update progress bar377updateProgressBar(percentCompleted);378}379380// Show upload rate381if (progressEvent.rate) {382console.log(`Upload rate: ${(progressEvent.rate / 1024).toFixed(2)} KB/s`);383}384}385});386387// Download progress388const response = await axios.get("https://api.example.com/download/largefile", {389responseType: "blob",390onDownloadProgress: (progressEvent) => {391if (progressEvent.total) {392const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);393console.log(`Download ${percentCompleted}% completed`);394395// Estimated time remaining396if (progressEvent.estimated) {397console.log(`ETA: ${progressEvent.estimated}s`);398}399}400}401});402```403404### Data Transformation405406Transform request and response data automatically.407408```typescript { .api }409interface AxiosRequestTransformer {410(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;411}412413interface AxiosResponseTransformer {414(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;415}416```417418**Usage Examples:**419420```typescript421import axios from "axios";422423// Custom request transformer424const api = axios.create({425transformRequest: [426function (data, headers) {427// Transform request data428if (data && typeof data === "object") {429// Convert dates to ISO strings430const transformed = { ...data };431Object.keys(transformed).forEach(key => {432if (transformed[key] instanceof Date) {433transformed[key] = transformed[key].toISOString();434}435});436return JSON.stringify(transformed);437}438return data;439},440...axios.defaults.transformRequest // Include default transformers441]442});443444// Custom response transformer445const api = axios.create({446transformResponse: [447...axios.defaults.transformResponse, // Include default transformers448function (data) {449// Parse date strings back to Date objects450if (data && typeof data === "object") {451Object.keys(data).forEach(key => {452if (typeof data[key] === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(data[key])) {453data[key] = new Date(data[key]);454}455});456}457return data;458}459]460});461462// Use transformed data463const user = await api.post("/users", {464name: "John",465birthDate: new Date("1990-01-01") // Automatically converted to ISO string466});467468console.log(user.data.birthDate instanceof Date); // true - converted back to Date469```470471### Timeout and Validation472473Request timeout and response validation configuration.474475**Usage Examples:**476477```typescript478import axios from "axios";479480// Timeout configuration481const response = await axios.get("https://api.example.com/data", {482timeout: 5000, // 5 seconds483timeoutErrorMessage: "Request took too long to complete"484});485486// Custom status validation487const response = await axios.get("https://api.example.com/data", {488validateStatus: function (status) {489// Accept 2xx and 3xx as successful490return status >= 200 && status < 400;491}492});493494// Accept specific error codes as successful495const response = await axios.get("https://api.example.com/optional-data", {496validateStatus: function (status) {497// Accept 200 (OK) and 404 (Not Found) as successful498return status === 200 || status === 404;499}500});501502if (response.status === 404) {503console.log("Data not found, using defaults");504} else {505console.log("Data retrieved:", response.data);506}507```