- Spec files
npm-axios
Describes: pkg:npm/axios@0.30.x
- Description
- Promise based HTTP client for the browser and node.js
- Author
- tessl
- Last updated
configuration.md docs/
1# Configuration23Comprehensive configuration system providing hierarchical configuration merging from global defaults, instance defaults, and request-specific overrides. Supports extensive customization of request behavior, timeouts, authentication, data transformation, and more.45## Capabilities67### Default Configuration Access89Access and modify the global default configuration that applies to all requests.1011```javascript { .api }12/**13* Global default configuration object14*/15axios.defaults: AxiosDefaults;16```1718**Usage Examples:**1920```javascript21// Set global base URL22axios.defaults.baseURL = 'https://api.example.com';2324// Set global timeout25axios.defaults.timeout = 10000;2627// Set global headers28axios.defaults.headers.common['Authorization'] = 'Bearer token123';29axios.defaults.headers.post['Content-Type'] = 'application/json';3031// View current defaults32console.log(axios.defaults.timeout); // 1000033console.log(axios.defaults.baseURL); // https://api.example.com34```3536### Request Configuration Options3738Complete configuration interface for customizing individual requests.3940```javascript { .api }41interface AxiosRequestConfig<D = any> {42/** Request URL */43url?: string;44/** HTTP method (defaults to 'get') */45method?: Method | string;46/** Base URL prepended to url unless url is absolute */47baseURL?: string;48/** Allow absolute URLs when using baseURL */49allowAbsoluteUrls?: boolean;50/** Functions to transform request data */51transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];52/** Functions to transform response data */53transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];54/** Request headers */55headers?: AxiosRequestHeaders;56/** URL parameters object */57params?: any;58/** URL parameters serializer configuration */59paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;60/** Request body data */61data?: D;62/** Request timeout in milliseconds (0 = no timeout) */63timeout?: number;64/** Timeout error message */65timeoutErrorMessage?: string;66/** Send cookies with cross-origin requests */67withCredentials?: boolean;68/** Custom adapter for handling requests */69adapter?: AxiosAdapter;70/** Basic authentication credentials */71auth?: AxiosBasicCredentials;72/** Response data type */73responseType?: ResponseType;74/** Response encoding (Node.js only) */75responseEncoding?: responseEncoding | string;76/** XSRF cookie name */77xsrfCookieName?: string;78/** XSRF header name */79xsrfHeaderName?: string;80/** Upload progress callback */81onUploadProgress?: (progressEvent: ProgressEvent) => void;82/** Download progress callback */83onDownloadProgress?: (progressEvent: ProgressEvent) => void;84/** Max request content length in bytes */85maxContentLength?: number;86/** Status code validation function */87validateStatus?: ((status: number) => boolean) | null;88/** Max request body length in bytes */89maxBodyLength?: number;90/** Max redirects to follow */91maxRedirects?: number;92/** Hook called before redirect */93beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;94/** Unix socket path (Node.js only) */95socketPath?: string | null;96/** HTTP agent (Node.js only) */97httpAgent?: any;98/** HTTPS agent (Node.js only) */99httpsAgent?: any;100/** Proxy configuration */101proxy?: AxiosProxyConfig | false;102/** Cancellation token (legacy) */103cancelToken?: CancelToken;104/** Decompress response body */105decompress?: boolean;106/** Transitional behavior options */107transitional?: TransitionalOptions;108/** AbortController signal (modern cancellation) */109signal?: GenericAbortSignal;110/** Insecure HTTP parser */111insecureHTTPParser?: boolean;112/** Environment-specific classes */113env?: {114FormData?: new (...args: any[]) => object;115};116/** Form data serialization options */117formSerializer?: FormSerializerOptions;118/** XSRF token function or boolean */119withXSRFToken?: boolean | ((config: AxiosRequestConfig) => boolean | undefined);120}121```122123**Usage Examples:**124125```javascript126// Comprehensive request configuration127const response = await axios({128method: 'post',129url: '/users',130baseURL: 'https://api.example.com',131timeout: 5000,132headers: {133'Content-Type': 'application/json',134'Authorization': 'Bearer token123'135},136params: { include: 'profile' },137data: { name: 'John', email: 'john@example.com' },138validateStatus: (status) => status < 500,139onUploadProgress: (event) => {140console.log(`Upload progress: ${(event.loaded / event.total) * 100}%`);141}142});143```144145### HTTP Methods146147Supported HTTP methods for the method configuration option.148149```javascript { .api }150type Method =151| 'get' | 'GET'152| 'delete' | 'DELETE'153| 'head' | 'HEAD'154| 'options' | 'OPTIONS'155| 'post' | 'POST'156| 'put' | 'PUT'157| 'patch' | 'PATCH'158| 'purge' | 'PURGE'159| 'link' | 'LINK'160| 'unlink' | 'UNLINK';161```162163### Response Types164165Available response data types for the responseType configuration option.166167```javascript { .api }168type ResponseType =169| 'arraybuffer' // ArrayBuffer object170| 'blob' // Blob object (browser only)171| 'document' // DOM Document (browser only)172| 'json' // JSON object (default)173| 'text' // String174| 'stream'; // Node.js readable stream175```176177**Usage Examples:**178179```javascript180// Download binary data181const response = await axios.get('/files/image.png', {182responseType: 'arraybuffer'183});184const imageData = response.data; // ArrayBuffer185186// Download as blob for file saving187const response = await axios.get('/files/document.pdf', {188responseType: 'blob'189});190const blob = response.data; // Blob object191192// Stream large file (Node.js)193const response = await axios.get('/files/large-file.zip', {194responseType: 'stream'195});196response.data.pipe(fs.createWriteStream('output.zip'));197```198199### Authentication Configuration200201Built-in support for HTTP Basic authentication.202203```javascript { .api }204interface AxiosBasicCredentials {205username: string;206password: string;207}208```209210**Usage Examples:**211212```javascript213// Basic authentication214const response = await axios.get('/protected', {215auth: {216username: 'john',217password: 'secret123'218}219});220221// Equivalent to setting Authorization header222const response = await axios.get('/protected', {223headers: {224'Authorization': 'Basic ' + btoa('john:secret123')225}226});227```228229### Proxy Configuration230231HTTP/HTTPS proxy support for Node.js environments.232233```javascript { .api }234interface AxiosProxyConfig {235host: string;236port: number;237auth?: {238username: string;239password: string;240};241protocol?: string;242}243```244245**Usage Examples:**246247```javascript248// HTTP proxy249const response = await axios.get('https://api.example.com/data', {250proxy: {251host: '127.0.0.1',252port: 8080253}254});255256// Authenticated proxy257const response = await axios.get('https://api.example.com/data', {258proxy: {259host: 'proxy.company.com',260port: 3128,261auth: {262username: 'proxyuser',263password: 'proxypass'264},265protocol: 'http'266}267});268269// Disable proxy270const response = await axios.get('https://api.example.com/data', {271proxy: false272});273```274275### Data Transformation276277Configure how request and response data is processed.278279```javascript { .api }280interface AxiosRequestTransformer {281(data: any, headers: AxiosRequestHeaders): any;282}283284interface AxiosResponseTransformer {285(data: any, headers?: AxiosResponseHeaders, status?: number): any;286}287```288289**Usage Examples:**290291```javascript292// Custom request transformer293axios.defaults.transformRequest = [294(data, headers) => {295// Transform data before sending296if (data && typeof data === 'object') {297// Add timestamp to all requests298data._timestamp = Date.now();299}300return JSON.stringify(data);301}302];303304// Custom response transformer305axios.defaults.transformResponse = [306(data) => {307// Parse and transform response308const parsed = JSON.parse(data);309310// Unwrap data from API wrapper311if (parsed && parsed.result) {312return parsed.result;313}314315return parsed;316}317];318319// Request-specific transformers320const response = await axios.post('/data', requestData, {321transformRequest: [322(data, headers) => {323// Custom transformation for this request324return btoa(JSON.stringify(data)); // Base64 encode325}326],327transformResponse: [328(data) => {329// Custom response parsing330return JSON.parse(atob(data)); // Base64 decode331}332]333});334```335336### Headers Configuration337338Flexible header management with method-specific defaults.339340```javascript { .api }341interface HeadersDefaults {342common: AxiosRequestHeaders; // Headers for all methods343delete: AxiosRequestHeaders; // Headers for DELETE requests344get: AxiosRequestHeaders; // Headers for GET requests345head: AxiosRequestHeaders; // Headers for HEAD requests346post: AxiosRequestHeaders; // Headers for POST requests347put: AxiosRequestHeaders; // Headers for PUT requests348patch: AxiosRequestHeaders; // Headers for PATCH requests349options?: AxiosRequestHeaders; // Headers for OPTIONS requests350purge?: AxiosRequestHeaders; // Headers for PURGE requests351link?: AxiosRequestHeaders; // Headers for LINK requests352unlink?: AxiosRequestHeaders; // Headers for UNLINK requests353}354```355356**Usage Examples:**357358```javascript359// Set headers for all requests360axios.defaults.headers.common['Authorization'] = 'Bearer token123';361axios.defaults.headers.common['User-Agent'] = 'MyApp/1.0';362363// Set headers for specific methods364axios.defaults.headers.post['Content-Type'] = 'application/json';365axios.defaults.headers.get['Accept'] = 'application/json';366367// Instance-specific headers368const apiClient = axios.create({369baseURL: 'https://api.example.com',370headers: {371common: {372'Authorization': 'Bearer instance-token'373},374post: {375'Content-Type': 'application/json'376}377}378});379380// Request-specific headers (highest priority)381const response = await axios.get('/data', {382headers: {383'Accept': 'application/xml', // Overrides default384'X-Custom': 'value' // Additional header385}386});387```388389### Timeout Configuration390391Configure request timeouts and error messages.392393```javascript { .api }394interface TimeoutConfig {395/** Timeout in milliseconds (0 = no timeout) */396timeout?: number;397/** Custom timeout error message */398timeoutErrorMessage?: string;399}400```401402**Usage Examples:**403404```javascript405// Global timeout406axios.defaults.timeout = 10000; // 10 seconds407408// Request-specific timeout409const response = await axios.get('/slow-endpoint', {410timeout: 30000, // 30 seconds for this request411timeoutErrorMessage: 'The request took too long to complete'412});413414// No timeout for specific request415const response = await axios.get('/streaming-data', {416timeout: 0 // No timeout417});418```419420### URL Parameter Serialization421422Configure how URL parameters are serialized.423424```javascript { .api }425interface ParamsSerializerOptions extends SerializerOptions {426encode?: ParamEncoder;427serialize?: CustomParamsSerializer;428}429430interface ParamEncoder {431(value: any, defaultEncoder: (value: any) => any): any;432}433434interface CustomParamsSerializer {435(params: Record<string, any>, options?: ParamsSerializerOptions): string;436}437```438439**Usage Examples:**440441```javascript442// Custom parameter encoding443const response = await axios.get('/search', {444params: {445q: 'hello world',446tags: ['javascript', 'api'],447nested: { key: 'value' }448},449paramsSerializer: {450encode: (value, defaultEncoder) => {451// Custom encoding logic452return encodeURIComponent(value);453},454serialize: (params) => {455// Custom serialization456return Object.keys(params)457.map(key => `${key}=${params[key]}`)458.join('&');459}460}461});462463// Array parameter handling464const response = await axios.get('/items', {465params: {466ids: [1, 2, 3],467categories: ['tech', 'news']468},469paramsSerializer: {470indexes: false, // ids=1&ids=2&ids=3 instead of ids[0]=1&ids[1]=2&ids[2]=3471}472});473```474475### Transitional Options476477Backward compatibility and transitional behavior configuration.478479```javascript { .api }480interface TransitionalOptions {481/** Silently parse JSON responses even if not JSON content type */482silentJSONParsing?: boolean;483/** Force JSON parsing for all responses */484forcedJSONParsing?: boolean;485/** Provide more descriptive timeout error messages */486clarifyTimeoutError?: boolean;487}488```489490**Usage Examples:**491492```javascript493// Configure transitional behavior494axios.defaults.transitional = {495silentJSONParsing: true, // Don't throw on JSON parse errors496forcedJSONParsing: false, // Only parse JSON for JSON content types497clarifyTimeoutError: true // Better timeout error messages498};499500// Request-specific transitional options501const response = await axios.get('/legacy-api', {502transitional: {503silentJSONParsing: false, // Strict JSON parsing for this request504forcedJSONParsing: true // Force JSON parsing regardless of content type505}506});507```508509### Status Code Validation510511Customize which HTTP status codes are considered successful.512513```javascript { .api }514/**515* Function to validate HTTP status codes516* @param status - HTTP status code517* @returns true if status should resolve promise, false if it should reject518*/519validateStatus?: ((status: number) => boolean) | null;520```521522**Usage Examples:**523524```javascript525// Default validation (200-299 are successful)526axios.defaults.validateStatus = (status) => status >= 200 && status < 300;527528// Accept 404 as successful for existence checks529const response = await axios.get('/users/123', {530validateStatus: (status) => status === 200 || status === 404531});532533if (response.status === 404) {534console.log('User not found');535} else {536console.log('User found:', response.data);537}538539// Treat all responses as successful (handle errors manually)540const response = await axios.get('/api/data', {541validateStatus: () => true542});543544if (response.status >= 400) {545console.log('Error response:', response.status);546} else {547console.log('Success:', response.data);548}549```