* ci: set hardened --ignore-scripts for all ci actions * docs: adds new docs platform * chore: remove un-needed ignore * chore: add sponsors data. adjust package.json to be of type module * fix: inconsistency between the docs and readme * fix: docs inconsistency * docs: update language and phrasing * style: fix issues with card styling * docs: update security.md with latest changes * docs: remove un-needed code * docs: fix inconsistencies with actual library function * ci: added deployment for docs * chore: added axios as dep for docs * docs: fix batch of errors * fix: bump esbuild as the version included is a risk
10 KiB
API reference
Below is a list of all the available functions and classes in the axios package. These functions may be used and imported in your project. All of these functions and classes are protected by our renewed promise to follow semantic versioning. This means that you can rely on these functions and classes to remain stable and unchanged in future releases unless a major version change is made.
Instance
The axios instance is the main object that you will use to make HTTP requests. It is a factory function that creates a new instance of the Axios class. The axios instance has a number of methods that you can use to make HTTP requests. These methods are documented in the Request aliases section of the documentation.
Classes
Axios
The Axios class is the main class that you will use to make HTTP requests. It is a factory function that creates a new instance of the Axios class. The Axios class has a number of methods that you can use to make HTTP requests. These methods are documented in the Request aliases section of the documentation.
constructor
Creates a new instance of the Axios class. The constructor takes an optional configuration object as an argument.
constructor(instanceConfig?: AxiosRequestConfig);
request
Handles request invocation and response resolution. This is the main method that you will use to make HTTP requests. It takes a configuration object as an argument and returns a promise that resolves to the response object.
request(configOrUrl: string | AxiosRequestConfig<D>, config: AxiosRequestConfig<D>): Promise<AxiosResponse<T>>;
CancelToken
The CancelToken class was based on the tc39/proposal-cancelable-promises proposal. It was used to create a token that could be used to cancel an HTTP request. The CancelToken class is now deprecated in favour of the AbortController API.
As of version 0.22.0, the CancelToken class is deprecated and will be removed in a future release. It is recommended that you use the AbortController API instead.
The class is exported mainly for backwards compatibility and will be removed in a future release. We also strongly discourage its use in new projects, we therefore are not documenting the API as use is discouraged.
Functions
AxiosError
The AxiosError class is an error class that is thrown when an HTTP request fails. It extends the Error class and adds additional properties to the error object.
constructor
Creates a new instance of the AxiosError class. The constructor takes an optional message, code, config, request, and response as arguments.
constructor(message?: string, code?: string, config?: InternalAxiosRequestConfig<D>, request?: any, response?: AxiosResponse<T, D>);
properties
The AxiosError class provides the following properties:
// Config instance.
config?: InternalAxiosRequestConfig<D>;
// Error code.
code?: string;
// Request instance.
request?: any;
// Response instance.
response?: AxiosResponse<T, D>;
// Boolean indicating if the error is an `AxiosError`.
isAxiosError: boolean;
// Error status code.
status?: number;
// Helper method to convert the error to a JSON object.
toJSON: () => object;
// Error cause.
cause?: Error;
AxiosHeaders
The AxiosHeaders class is a utility class that is used to manage HTTP headers. It provides methods for manipulating headers, such as adding, removing, and getting headers.
Only the main methods are documented here. For a full list of methods, please refer to the type declaration file.
constructor
Creates a new instance of the AxiosHeaders class. The constructor takes an optional headers object as an argument.
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
set
Adds a header to the headers object.
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
get
Gets a header from the headers object.
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
has
Checks if a header exists in the headers object.
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete
Removes a header from the headers object.
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear
Removes all headers from the headers object.
clear(matcher?: AxiosHeaderMatcher): boolean;
normalize
Normalizes the headers object.
normalize(format: boolean): AxiosHeaders;
concat
Concatenates headers objects.
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
toJSON
Converts the headers object to a JSON object.
toJSON(asStrings?: boolean): RawAxiosHeaders;
CanceledError
The CanceledError class is an error class that is thrown when an HTTP request is canceled. It extends the AxiosError class.
Cancel
The Cancel class is an alias for the CanceledError class. It is exported for backwards compatibility and will be removed in a future release.
isCancel
A function that checks if an error is a CanceledError. Useful for distinguishing intentional cancellations from unexpected errors.
isCancel(value: any): boolean;
import axios from "axios";
const controller = new AbortController();
axios.get("/api/data", { signal: controller.signal }).catch((error) => {
if (axios.isCancel(error)) {
console.log("Request was cancelled:", error.message);
} else {
console.error("Unexpected error:", error);
}
});
controller.abort("User navigated away");
isAxiosError
A function that checks if an error is an AxiosError. Use this in catch blocks to safely access axios-specific error properties like error.response and error.config.
isAxiosError(value: any): value is AxiosError;
import axios from "axios";
try {
await axios.get("/api/resource");
} catch (error) {
if (axios.isAxiosError(error)) {
// error.response, error.config, error.code are all available
console.error("HTTP error", error.response?.status, error.message);
} else {
// A non-axios error (e.g. a programming mistake)
throw error;
}
}
all
The all function is a utility function that takes an array of promises and returns a single promise that resolves when all of the promises in the array have resolved. The all function is now deprecated in favour of the Promise.all method. It is recommended that you use the Promise.all method instead.
As of version 0.22.0, the all function is deprecated and will be removed in a future release. It is recommended that you use the Promise.all method instead.
spread
The spread function is a utility function that can be used to spread an array of arguments into a function call. This is useful when you have an array of arguments that you want to pass to a function that takes multiple arguments.
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
toFormData
Converts a plain JavaScript object (or a nested one) to a FormData instance. Useful when you want to programmatically build multipart form data from an object.
toFormData(sourceObj: object, formData?: FormData, options?: FormSerializerOptions): FormData;
import { toFormData } from "axios";
const data = { name: "Jay", avatar: fileBlob };
const form = toFormData(data);
// form is now a FormData instance ready to post
await axios.post("/api/users", form);
formToJSON
Converts a FormData instance back to a plain JavaScript object. Useful for reading form data in a structured format.
formToJSON(form: FormData): object;
import { formToJSON } from "axios";
const form = new FormData();
form.append("name", "Jay");
form.append("role", "admin");
const obj = formToJSON(form);
console.log(obj); // { name: "Jay", role: "admin" }
getAdapter
Resolves and returns an adapter function by name or by passing an array of candidate names. axios uses this internally to select the best available adapter for the current environment.
getAdapter(adapters: string | string[]): AxiosAdapter;
import { getAdapter } from "axios";
// Get the fetch adapter explicitly
const fetchAdapter = getAdapter("fetch");
// Get the best available adapter from a priority list
const adapter = getAdapter(["fetch", "xhr", "http"]);
mergeConfig
Merges two axios config objects together, applying the same deep-merge strategy that axios uses internally when combining defaults with per-request options. Later values take precedence.
mergeConfig<T>(config1: AxiosRequestConfig<T>, config2: AxiosRequestConfig<T>): AxiosRequestConfig<T>;
import { mergeConfig } from "axios";
const base = { baseURL: "https://api.example.com", timeout: 5000 };
const override = { timeout: 10000, headers: { "X-Custom": "value" } };
const merged = mergeConfig(base, override);
// { baseURL: "https://api.example.com", timeout: 10000, headers: { "X-Custom": "value" } }
Constants
HttpStatusCode
An object that contains a list of HTTP status codes as named constants. Use this to write readable conditionals instead of bare numbers.
import axios, { HttpStatusCode } from "axios";
try {
const response = await axios.get("/api/resource");
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response?.status === HttpStatusCode.NotFound) {
console.error("Resource not found");
} else if (error.response?.status === HttpStatusCode.Unauthorized) {
console.error("Authentication required");
}
}
}
Miscellaneous
VERSION
The current version of the axios package. This is a string that represents the version number of the package. It is updated with each release of the package.