diff --git a/index.d.cts b/index.d.cts index b830cb9a58..844cda67b7 100644 --- a/index.d.cts +++ b/index.d.cts @@ -18,16 +18,9 @@ type AxiosHeaderGetter = ((parser?: RegExp) => RegExpExecArray | null) | type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean; -type MaxUploadRate = number; - -type MaxDownloadRate = number; - -type Milliseconds = number; - declare class AxiosHeaders { constructor( - headers?: RawAxiosHeaders | AxiosHeaders, - defaultHeaders?: RawAxiosHeaders | AxiosHeaders + headers?: RawAxiosHeaders | AxiosHeaders ); set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; @@ -44,12 +37,16 @@ declare class AxiosHeaders { normalize(format: boolean): AxiosHeaders; + concat(...targets: Array): AxiosHeaders; + toJSON(asStrings?: boolean): RawAxiosHeaders; static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; static accessor(header: string | string[]): AxiosHeaders; + static concat(...targets: Array): AxiosHeaders; + setContentType: AxiosHeaderSetter; getContentType: AxiosHeaderGetter; hasContentType: AxiosHeaderTester; @@ -199,7 +196,7 @@ declare namespace axios { type RawAxiosRequestHeaders = Partial; - type AxiosRequestHeaders = Partial & AxiosHeaders; + type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; type RawAxiosResponseHeaders = Partial & { "set-cookie"?: string[] @@ -321,6 +318,10 @@ declare namespace axios { serialize?: CustomParamsSerializer; } + type MaxUploadRate = number; + + type MaxDownloadRate = number; + type BrowserProgressEvent = any; interface AxiosProgressEvent { @@ -335,20 +336,26 @@ declare namespace axios { event?: BrowserProgressEvent; } + type Milliseconds = number; + + type AxiosAdapterName = 'xhr' | 'http' | string; + + type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + interface AxiosRequestConfig { url?: string; method?: Method | string; baseURL?: string; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; - headers?: RawAxiosRequestHeaders; + headers?: RawAxiosRequestHeaders | AxiosHeaders; params?: any; paramsSerializer?: ParamsSerializerOptions; data?: D; timeout?: Milliseconds; timeoutErrorMessage?: string; withCredentials?: boolean; - adapter?: AxiosAdapter; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; auth?: AxiosBasicCredentials; responseType?: ResponseType; responseEncoding?: responseEncoding | string; @@ -396,7 +403,7 @@ declare namespace axios { } interface CreateAxiosDefaults extends Omit, 'headers'> { - headers?: RawAxiosRequestHeaders | Partial; + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; } interface AxiosResponse { @@ -485,6 +492,7 @@ declare namespace axios { isAxiosError(payload: any): payload is AxiosError; toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + AxiosHeaders: typeof AxiosHeaders; } } diff --git a/index.d.ts b/index.d.ts index a6cb8ff2ca..35d50e3c1f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -71,7 +71,7 @@ export class AxiosHeaders { export type RawAxiosRequestHeaders = Partial; -export type AxiosRequestHeaders = Partial & AxiosHeaders; +export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; export type RawAxiosResponseHeaders = Partial & { "set-cookie"?: string[] @@ -289,7 +289,7 @@ export interface AxiosRequestConfig { baseURL?: string; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; - headers?: RawAxiosRequestHeaders; + headers?: RawAxiosRequestHeaders | AxiosHeaders; params?: any; paramsSerializer?: ParamsSerializerOptions; data?: D; @@ -344,7 +344,7 @@ export interface AxiosDefaults extends Omit, 'hea } export interface CreateAxiosDefaults extends Omit, 'headers'> { - headers?: RawAxiosRequestHeaders | Partial; + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; } export interface AxiosResponse { @@ -499,6 +499,7 @@ export interface AxiosStatic extends AxiosInstance { CancelToken: CancelTokenStatic; Axios: typeof Axios; AxiosError: typeof AxiosError; + HttpStatusCode: typeof HttpStatusCode; readonly VERSION: string; isCancel: typeof isCancel; all: typeof all; diff --git a/package.json b/package.json index 0ea55fdccf..a19904f349 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "type": "module", "types": "index.d.ts", "scripts": { - "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:exports && npm run test:dtslint", + "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint && npm run test:exports", "test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js", "test:dtslint": "node bin/ssl_hotfix.js dtslint", "test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit", diff --git a/test/module/test.js b/test/module/test.js index 166e649ce6..3410ca2a88 100644 --- a/test/module/test.js +++ b/test/module/test.js @@ -14,6 +14,16 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); const exec = util.promisify(cp.exec); +const spawn = (command, args) => new Promise((resolve, reject) => { + cp.spawn(command, args, { + shell : true, + stdio: 'inherit' + }).once('error', reject).on( + 'close', + (code) => code ? reject(new Error(`Exit code ${code}`)) : resolve() + ); +}); + const {Axios} = axiosFactory; const ignoreList = ['default']; @@ -134,4 +144,40 @@ describe('module', function () { await exec(`npm test --prefix ${pkgPath}`, {}); }); }); + + describe('typings', () => { + describe('ESM', ()=> { + const pkgPath = path.join(__dirname, './typings/esm'); + + after(async ()=> { + await remove(path.join(pkgPath, './node_modules')); + }); + + it('should pass types check', async function () { + this.timeout(30000); + + await spawn(`npm test --prefix ${pkgPath}`, [], { + shell : true, + stdio: 'pipe' + }); + }); + }); + + describe('CommonJS', ()=> { + const pkgPath = path.join(__dirname, './typings/cjs'); + + after(async ()=> { + await remove(path.join(pkgPath, './node_modules')); + }); + + it('should pass types check', async function () { + this.timeout(30000); + + await spawn(`npm test --prefix ${pkgPath}`, [], { + shell : true, + stdio: 'pipe' + }); + }); + }); + }); }); diff --git a/test/typescript/axios.cts b/test/typescript/axios.cts deleted file mode 100644 index 6d25deedfa..0000000000 --- a/test/typescript/axios.cts +++ /dev/null @@ -1,443 +0,0 @@ -import axios = require('axios'); - -const config: axios.AxiosRequestConfig = { - url: '/user', - method: 'get', - baseURL: 'https://api.example.com/', - transformRequest: (data: any) => '{"foo":"bar"}', - transformResponse: [ - (data: any) => ({ baz: 'qux' }) - ], - headers: { 'X-FOO': 'bar' }, - params: { id: 12345 }, - paramsSerializer: { - indexes: true, - encode: (value: any) => value, - serialize: (value: Record, options?: axios.ParamsSerializerOptions) => String(value) - }, - data: { foo: 'bar' }, - timeout: 10000, - withCredentials: true, - auth: { - username: 'janedoe', - password: 's00pers3cret' - }, - responseType: 'json', - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - onUploadProgress: (progressEvent: axios.AxiosProgressEvent) => {}, - onDownloadProgress: (progressEvent: axios.AxiosProgressEvent) => {}, - maxContentLength: 2000, - maxBodyLength: 2000, - validateStatus: (status: number) => status >= 200 && status < 300, - maxRedirects: 5, - proxy: { - host: '127.0.0.1', - port: 9000 - }, - cancelToken: new axios.CancelToken((cancel: axios.Canceler) => {}) -}; - -const nullValidateStatusConfig: axios.AxiosRequestConfig = { - validateStatus: null -}; - -const undefinedValidateStatusConfig: axios.AxiosRequestConfig = { - validateStatus: undefined -}; - -const handleResponse = (response: axios.AxiosResponse) => { - console.log(response.data); - console.log(response.status); - console.log(response.statusText); - console.log(response.headers); - console.log(response.config); -}; - -const handleError = (error: axios.AxiosError) => { - if (error.response) { - console.log(error.response.data); - console.log(error.response.status); - console.log(error.response.headers); - } else { - console.log(error.message); - } -}; - -axios(config) - .then(handleResponse) - .catch(handleError); - -axios.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); - -axios.head('/user') - .then(handleResponse) - .catch(handleError); - -axios.options('/user') - .then(handleResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleResponse) - .catch(handleError); - -axios.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); - -axios.put('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -axios.patch('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -// Typed methods -interface UserCreationDef { - name: string; -} - -interface User { - id: number; - name: string; -} - -// with default axios.AxiosResponse result - -const handleUserResponse = (response: axios.AxiosResponse) => { - console.log(response.data.id); - console.log(response.data.name); - console.log(response.status); - console.log(response.statusText); - console.log(response.headers); - console.log(response.config); -}; - -axios.get('/user?id=12345') - .then(handleUserResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleUserResponse) - .catch(handleError); - -axios.head('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.options('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.post('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -axios.post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) - .then(handleUserResponse) - .catch(handleError); - -axios.put('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -axios.patch('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -// (Typed methods) with custom response type - -const handleStringResponse = (response: string) => { - console.log(response); -}; - -axios.get('/user?id=12345') - .then(handleStringResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleStringResponse) - .catch(handleError); - -axios.head('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.options('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.post, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleStringResponse) - .catch(handleError); - -axios.put, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.patch, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.request({ - method: 'get', - url: '/user?id=12345' -}) - .then(handleStringResponse) - .catch(handleError); - -// Instances - -const instance1: axios.AxiosInstance = axios.create(); -const instance2: axios.AxiosInstance = axios.create(config); - -instance1(config) - .then(handleResponse) - .catch(handleError); - -instance1.request(config) - .then(handleResponse) - .catch(handleError); - -instance1.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); - -instance1.options('/user') - .then(handleResponse) - .catch(handleError); - -instance1.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); - -instance1.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); - -// Defaults - -axios.defaults.headers['X-FOO']; - -axios.defaults.baseURL = 'https://api.example.com/'; -axios.defaults.headers.common['Accept'] = 'application/json'; -axios.defaults.headers.post['X-FOO'] = 'bar'; -axios.defaults.timeout = 2500; - -instance1.defaults.baseURL = 'https://api.example.com/'; -instance1.defaults.headers.common['Accept'] = 'application/json'; -instance1.defaults.headers.post['X-FOO'] = 'bar'; -instance1.defaults.timeout = 2500; - -// axios create defaults - -axios.create({ headers: { foo: 'bar' } }); -axios.create({ headers: { common: { foo: 'bar' } } }); -axios.create({ - headers: { - 'Content-Type': 'application/json', - }, - formSerializer: { - indexes: null, - }, - paramsSerializer: { - indexes: null, - }, -}); - -// Interceptors - -const requestInterceptorId: number = axios.interceptors.request.use( - (config: axios.AxiosRequestConfig) => config, - (error: any) => Promise.reject(error) -); - -axios.interceptors.request.eject(requestInterceptorId); - -axios.interceptors.request.use( - (config: axios.AxiosRequestConfig) => Promise.resolve(config), - (error: any) => Promise.reject(error) -); - -axios.interceptors.request.use((config: axios.AxiosRequestConfig) => config); -axios.interceptors.request.use((config: axios.AxiosRequestConfig) => Promise.resolve(config)); - -const responseInterceptorId: number = axios.interceptors.response.use( - (response: axios.AxiosResponse) => response, - (error: any) => Promise.reject(error) -); - -axios.interceptors.response.eject(responseInterceptorId); - -axios.interceptors.response.use( - (response: axios.AxiosResponse) => Promise.resolve(response), - (error: any) => Promise.reject(error) -); - -const voidRequestInterceptorId = axios.interceptors.request.use( - // @ts-expect-error -- Must return an axios.AxiosRequestConfig (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) -); -const voidResponseInterceptorId = axios.interceptors.response.use( - // @ts-expect-error -- Must return an axios.AxiosResponse (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) -); -axios.interceptors.request.eject(voidRequestInterceptorId); -axios.interceptors.response.eject(voidResponseInterceptorId); - -axios.interceptors.response.use((response: axios.AxiosResponse) => response); -axios.interceptors.response.use((response: axios.AxiosResponse) => Promise.resolve(response)); - -axios.interceptors.request.clear(); -axios.interceptors.response.clear(); - -// Adapters - -const adapter: axios.AxiosAdapter = (config: axios.AxiosRequestConfig) => { - const response: axios.AxiosResponse = { - data: { foo: 'bar' }, - status: 200, - statusText: 'OK', - headers: { 'X-FOO': 'bar' }, - config - }; - return Promise.resolve(response); -}; - -axios.defaults.adapter = adapter; - -// axios.all - -const promises = [ - Promise.resolve(1), - Promise.resolve(2) -]; - -const promise: Promise = axios.all(promises); - -// axios.spread - -const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; -const fn2: (arr: number[]) => string = axios.spread(fn1); - -// Promises - -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo') - .then((value: string) => {}); - -axios.get('/user') - .then((response: axios.AxiosResponse) => Promise.resolve('foo')) - .then((value: string) => {}); - -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo', (error: any) => 'bar') - .then((value: string) => {}); - -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo', (error: any) => 123) - .then((value: string | number) => {}); - -axios.get('/user') - .catch((error: any) => 'foo') - .then((value) => {}); - -axios.get('/user') - .catch((error: any) => Promise.resolve('foo')) - .then((value) => {}); - -// axios.Cancellation - -const source: axios.CancelTokenSource = axios.CancelToken.source(); - -axios.get('/user', { - cancelToken: source.token -}).catch((thrown: axios.AxiosError | axios.Cancel) => { - if (axios.isCancel(thrown)) { - const cancel: axios.Cancel = thrown; - console.log(cancel.message); - } -}); - -source.cancel('Operation has been axios.Canceled.'); - -// axios.AxiosError - -axios.get('/user') - .catch((error) => { - if (axios.isAxiosError(error)) { - const axiosError: axios.AxiosError = error; - } - }); - -// FormData - -axios.toFormData({x: 1}, new FormData()); - -// AbortSignal - -axios.get('/user', {signal: new AbortController().signal}); - -// AxiosHeaders methods - -axios.get('/user', { - transformRequest: (data, headers) => { - headers.setContentType('text/plain'); - headers['Foo'] = 'bar'; - }, - - transformResponse: (data, headers) => { - headers.has('foo'); - } -}); - -// Max Rate - -axios.get('/user', { - maxRate: 1000 -}); - -axios.get('/user', { - maxRate: [1000, 1000], -}); - -// Node progress - -axios.get('/user', { - onUploadProgress: (e) => { - console.log(e.loaded); - console.log(e.total); - console.log(e.progress); - console.log(e.rate); - } -}); diff --git a/test/typescript/axios.ts b/test/typescript/axios.ts deleted file mode 100644 index 1be0557e9a..0000000000 --- a/test/typescript/axios.ts +++ /dev/null @@ -1,513 +0,0 @@ -import axios, { - AxiosRequestConfig, - AxiosResponse, - AxiosError, - AxiosInstance, - AxiosAdapter, - Cancel, - CancelTokenSource, - Canceler, - AxiosProgressEvent, - ParamsSerializerOptions, - toFormData, - formToJSON, - all, - isCancel, - isAxiosError, - spread -} from 'axios'; - -const config: AxiosRequestConfig = { - url: '/user', - method: 'get', - baseURL: 'https://api.example.com/', - transformRequest: (data: any) => '{"foo":"bar"}', - transformResponse: [ - (data: any) => ({ baz: 'qux' }) - ], - headers: { 'X-FOO': 'bar' }, - params: { id: 12345 }, - paramsSerializer: { - indexes: true, - encode: (value: any) => value, - serialize: (value: Record, options?: ParamsSerializerOptions) => String(value) - }, - data: { foo: 'bar' }, - timeout: 10000, - withCredentials: true, - auth: { - username: 'janedoe', - password: 's00pers3cret' - }, - responseType: 'json', - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - onUploadProgress: (progressEvent: AxiosProgressEvent) => {}, - onDownloadProgress: (progressEvent: AxiosProgressEvent) => {}, - maxContentLength: 2000, - maxBodyLength: 2000, - validateStatus: (status: number) => status >= 200 && status < 300, - maxRedirects: 5, - proxy: { - host: '127.0.0.1', - port: 9000 - }, - cancelToken: new axios.CancelToken((cancel: Canceler) => {}) -}; - -const nullValidateStatusConfig: AxiosRequestConfig = { - validateStatus: null -}; - -const undefinedValidateStatusConfig: AxiosRequestConfig = { - validateStatus: undefined -}; - -const handleResponse = (response: AxiosResponse) => { - console.log(response.data); - console.log(response.status); - console.log(response.statusText); - console.log(response.headers); - console.log(response.config); -}; - -const handleError = (error: AxiosError) => { - if (error.response) { - console.log(error.response.data); - console.log(error.response.status); - console.log(error.response.headers); - } else { - console.log(error.message); - } -}; - -axios(config) - .then(handleResponse) - .catch(handleError); - -axios.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); - -axios.head('/user') - .then(handleResponse) - .catch(handleError); - -axios.options('/user') - .then(handleResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleResponse) - .catch(handleError); - -axios.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); - -axios.put('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -axios.patch('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -// Typed methods -interface UserCreationDef { - name: string; -} - -interface User { - id: number; - name: string; -} - -// with default AxiosResponse result - -const handleUserResponse = (response: AxiosResponse) => { - console.log(response.data.id); - console.log(response.data.name); - console.log(response.status); - console.log(response.statusText); - console.log(response.headers); - console.log(response.config); -}; - -axios.get('/user?id=12345') - .then(handleUserResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleUserResponse) - .catch(handleError); - -axios.head('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.options('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleUserResponse) - .catch(handleError); - -axios.post('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -axios.post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) - .then(handleUserResponse) - .catch(handleError); - -axios.put('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -axios.patch('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -// (Typed methods) with custom response type - -const handleStringResponse = (response: string) => { - console.log(response); -}; - -axios.get('/user?id=12345') - .then(handleStringResponse) - .catch(handleError); - -axios.get('/user', { params: { id: 12345 } }) - .then(handleStringResponse) - .catch(handleError); - -axios.head('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.options('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.delete('/user') - .then(handleStringResponse) - .catch(handleError); - -axios.post, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleStringResponse) - .catch(handleError); - -axios.put, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.patch, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); - -axios.request({ - method: 'get', - url: '/user?id=12345' -}) - .then(handleStringResponse) - .catch(handleError); - -// Instances - -const instance1: AxiosInstance = axios.create(); -const instance2: AxiosInstance = axios.create(config); - -instance1(config) - .then(handleResponse) - .catch(handleError); - -instance1.request(config) - .then(handleResponse) - .catch(handleError); - -instance1.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); - -instance1.options('/user') - .then(handleResponse) - .catch(handleError); - -instance1.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); - -instance1.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); - -instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); - -// Defaults - -axios.defaults.headers['X-FOO']; - -axios.defaults.baseURL = 'https://api.example.com/'; -axios.defaults.headers.common['Accept'] = 'application/json'; -axios.defaults.headers.post['X-FOO'] = 'bar'; -axios.defaults.timeout = 2500; - -instance1.defaults.baseURL = 'https://api.example.com/'; -instance1.defaults.headers.common['Accept'] = 'application/json'; -instance1.defaults.headers.post['X-FOO'] = 'bar'; -instance1.defaults.timeout = 2500; - -// axios create defaults - -axios.create({ headers: { foo: 'bar' } }); -axios.create({ headers: { common: { foo: 'bar' } } }); -axios.create({ - headers: { - 'Content-Type': 'application/json', - }, - formSerializer: { - indexes: null, - }, - paramsSerializer: { - indexes: null, - }, -}); - -// Interceptors - -const requestInterceptorId: number = axios.interceptors.request.use( - (config: AxiosRequestConfig) => config, - (error: any) => Promise.reject(error) -); - -axios.interceptors.request.eject(requestInterceptorId); - -axios.interceptors.request.use( - (config: AxiosRequestConfig) => Promise.resolve(config), - (error: any) => Promise.reject(error) -); - -axios.interceptors.request.use((config: AxiosRequestConfig) => config); -axios.interceptors.request.use((config: AxiosRequestConfig) => Promise.resolve(config)); - -const responseInterceptorId: number = axios.interceptors.response.use( - (response: AxiosResponse) => response, - (error: any) => Promise.reject(error) -); - -axios.interceptors.response.eject(responseInterceptorId); - -axios.interceptors.response.use( - (response: AxiosResponse) => Promise.resolve(response), - (error: any) => Promise.reject(error) -); - -const voidRequestInterceptorId = axios.interceptors.request.use( - // @ts-expect-error -- Must return an AxiosRequestConfig (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) -); -const voidResponseInterceptorId = axios.interceptors.response.use( - // @ts-expect-error -- Must return an AxiosResponse (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) -); -axios.interceptors.request.eject(voidRequestInterceptorId); -axios.interceptors.response.eject(voidResponseInterceptorId); - -axios.interceptors.response.use((response: AxiosResponse) => response); -axios.interceptors.response.use((response: AxiosResponse) => Promise.resolve(response)); - -axios.interceptors.request.clear(); -axios.interceptors.response.clear(); - -// Adapters - -const adapter: AxiosAdapter = (config: AxiosRequestConfig) => { - const response: AxiosResponse = { - data: { foo: 'bar' }, - status: 200, - statusText: 'OK', - headers: { 'X-FOO': 'bar' }, - config - }; - return Promise.resolve(response); -}; - -axios.defaults.adapter = adapter; - -// axios.all - -const promises = [ - Promise.resolve(1), - Promise.resolve(2) -]; - -const promise: Promise = axios.all(promises); - -// axios.all named export - -(() => { - const promises = [ - Promise.resolve(1), - Promise.resolve(2) - ]; - - const promise: Promise = all(promises); -})(); - -// axios.spread - -const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; -const fn2: (arr: number[]) => string = axios.spread(fn1); - -// axios.spread named export -(() => { - const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; - const fn2: (arr: number[]) => string = spread(fn1); -})(); - -// Promises - -axios.get('/user') - .then((response: AxiosResponse) => 'foo') - .then((value: string) => {}); - -axios.get('/user') - .then((response: AxiosResponse) => Promise.resolve('foo')) - .then((value: string) => {}); - -axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 'bar') - .then((value: string) => {}); - -axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 123) - .then((value: string | number) => {}); - -axios.get('/user') - .catch((error: any) => 'foo') - .then((value) => {}); - -axios.get('/user') - .catch((error: any) => Promise.resolve('foo')) - .then((value) => {}); - -// Cancellation - -const source: CancelTokenSource = axios.CancelToken.source(); - -axios.get('/user', { - cancelToken: source.token -}).catch((thrown: AxiosError | Cancel) => { - if (axios.isCancel(thrown)) { - const cancel: Cancel = thrown; - console.log(cancel.message); - } - - // named export - if (isCancel(thrown)) { - const cancel: Cancel = thrown; - console.log(cancel.message); - } -}); - -source.cancel('Operation has been canceled.'); - -// AxiosError - -axios.get('/user') - .catch((error) => { - if (axios.isAxiosError(error)) { - const axiosError: AxiosError = error; - } - - // named export - - if (isAxiosError(error)) { - const axiosError: AxiosError = error; - } - }); - -// FormData - -axios.toFormData({x: 1}, new FormData()); - -// named export -toFormData({x: 1}, new FormData()); - -// formToJSON - -axios.toFormData(new FormData()); - -// named export -formToJSON(new FormData()); - -// AbortSignal - -axios.get('/user', {signal: new AbortController().signal}); - -// AxiosHeaders methods - -axios.get('/user', { - transformRequest: (data, headers) => { - headers.setContentType('text/plain'); - headers['Foo'] = 'bar'; - }, - - transformResponse: (data, headers) => { - headers.has('foo'); - } -}); - -// Max Rate - -axios.get('/user', { - maxRate: 1000 -}); - -axios.get('/user', { - maxRate: [1000, 1000], -}); - -// Node progress - -axios.get('/user', { - onUploadProgress: (e) => { - console.log(e.loaded); - console.log(e.total); - console.log(e.progress); - console.log(e.rate); - } -}); - -// adapters - -axios.get('/user', { - adapter: 'xhr' -}); - -axios.get('/user', { - adapter: 'http' -}); - -axios.get('/user', { - adapter: ['xhr', 'http'] -});