Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed & Imporoved AxiosHeaders class #5224

Merged
merged 4 commits into from Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -7,3 +7,6 @@ typings/
coverage/
test/typescript/axios.js*
sauce_connect.log
test/module/cjs/node_modules/
test/module/cjs/package-lock.json
backup/
1 change: 1 addition & 0 deletions .npmignore
Expand Up @@ -16,3 +16,4 @@ Gruntfile.js
karma.conf.js
webpack.*.js
sauce_connect.log
backup/
23 changes: 12 additions & 11 deletions CHANGELOG.md
Expand Up @@ -222,23 +222,24 @@
## [1.1.3] - 2022-10-15

### Added
Added custom params serializer support [#5113](https://github.com/axios/axios/pull/5113)

- Added custom params serializer support [#5113](https://github.com/axios/axios/pull/5113)

### Fixed

Fixed top-level export to keep them in-line with static properties [#5109](https://github.com/axios/axios/pull/5109)
Stopped including null values to query string. [#5108](https://github.com/axios/axios/pull/5108)
Restored proxy config backwards compatibility with 0.x [#5097](https://github.com/axios/axios/pull/5097)
Added back AxiosHeaders in AxiosHeaderValue [#5103](https://github.com/axios/axios/pull/5103)
Pin CDN install instructions to a specific version [#5060](https://github.com/axios/axios/pull/5060)
Handling of array values fixed for AxiosHeaders [#5085](https://github.com/axios/axios/pull/5085)
- Fixed top-level export to keep them in-line with static properties [#5109](https://github.com/axios/axios/pull/5109)
- Stopped including null values to query string. [#5108](https://github.com/axios/axios/pull/5108)
- Restored proxy config backwards compatibility with 0.x [#5097](https://github.com/axios/axios/pull/5097)
- Added back AxiosHeaders in AxiosHeaderValue [#5103](https://github.com/axios/axios/pull/5103)
- Pin CDN install instructions to a specific version [#5060](https://github.com/axios/axios/pull/5060)
- Handling of array values fixed for AxiosHeaders [#5085](https://github.com/axios/axios/pull/5085)

### Chores

docs: match badge style, add link to them [#5046](https://github.com/axios/axios/pull/5046)
chore: fixing comments typo [#5054](https://github.com/axios/axios/pull/5054)
chore: update issue template [#5061](https://github.com/axios/axios/pull/5061)
chore: added progress capturing section to the docs; [#5084](https://github.com/axios/axios/pull/5084)
- docs: match badge style, add link to them [#5046](https://github.com/axios/axios/pull/5046)
- chore: fixing comments typo [#5054](https://github.com/axios/axios/pull/5054)
- chore: update issue template [#5061](https://github.com/axios/axios/pull/5061)
- chore: added progress capturing section to the docs; [#5084](https://github.com/axios/axios/pull/5084)

### Contributors to this release

Expand Down
1 change: 1 addition & 0 deletions ECOSYSTEM.md
Expand Up @@ -20,6 +20,7 @@ This is a list of axios related libraries and resources. If you have a suggestio
* [axios-endpoints](https://github.com/renancaraujo/axios-endpoints) - Axios endpoints helps you to create a more concise endpoint mapping with axios.
* [axios-multi-api](https://github.com/MattCCC/axios-multi-api) - Easy API handling whenever there are many endpoints to add. It helps to make Axios requests in an easy and declarative manner.
* [axios-url-template](https://github.com/rafw87/axios-url-template) - Axios interceptor adding support for URL templates.
* [zodios](https://www.zodios.org) - Typesafe API client based on axios

### Logging and debugging

Expand Down
2 changes: 1 addition & 1 deletion UPGRADE_GUIDE.md → MIGRATION_GUIDE.md
@@ -1,3 +1,3 @@
# Upgrade Guide
# Migration Guide

## 0.x.x -> 1.1.0
69 changes: 49 additions & 20 deletions README.md
Expand Up @@ -35,6 +35,8 @@
- [Features](#features)
- [Browser Support](#browser-support)
- [Installing](#installing)
- [Package manager](#package-manager)
- [CDN](#cdn)
- [Example](#example)
- [Axios API](#axios-api)
- [Request method aliases](#request-method-aliases)
Expand Down Expand Up @@ -93,6 +95,8 @@ Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |

## Installing

### Package manager

Using npm:

```bash
Expand All @@ -117,7 +121,39 @@ Using pnpm:
$ pnpm add axios
```

Using jsDelivr CDN:
Once the package is installed, you can import the library using `import` or `require` approach:

```js
import axios, {isCancel, AxiosError} from 'axios';
```

You can also use the default export, since the named export is just a re-export from the Axios factory:

```js
import axios from 'axios';

console.log(axios.isCancel('something'));
````

If you use `require` for importing, **only default export is available**:

```js
const axios = require('axios');

console.log(axios.isCancel('something'));
```

For cases where something went wrong when trying to import a module into a custom or legacy environment,
you can try importing the module package directly:

```js
const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
```

### CDN

Using jsDelivr CDN (ES5 UMD browser module):

```html
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
Expand All @@ -131,19 +167,12 @@ Using unpkg CDN:

## Example

### note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
> **Note** CommonJS usage
> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:

```js
const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings
```

Performing a `GET` request

```js
const axios = require('axios').default;
import axios from 'axios';
//const axios = require('axios'); // legacy way

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
Expand Down Expand Up @@ -797,7 +826,7 @@ controller.abort()

You can also cancel a request using a *CancelToken*.

> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).

> This API is deprecated since v0.22.0 and shouldn't be used in new projects

Expand Down Expand Up @@ -853,7 +882,7 @@ cancel();

### URLSearchParams

By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded` format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers, [and Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018).
By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded` format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers,and [ Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018).

```js
const params = new URLSearchParams({ foo: 'bar' });
Expand Down Expand Up @@ -917,7 +946,7 @@ await axios.postForm('https://postman-echo.com/post', data,
);
```

The server will handle it as
The server will handle it as:

```js
{
Expand Down Expand Up @@ -1259,11 +1288,11 @@ You can use Gitpod, an online IDE(which is free for Open Source) for contributin

## Resources

* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
* [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
* [Upgrade Guide](https://github.com/axios/axios/blob/v1.x/UPGRADE_GUIDE.md)
* [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)

## Credits

Expand Down
2 changes: 1 addition & 1 deletion examples/get/index.html
Expand Up @@ -18,7 +18,7 @@ <h1>axios.get</h1>
'<img src="https://avatars.githubusercontent.com/u/' + person.avatar + '?s=50" class="col-md-1"/>' +
'<div class="col-md-3">' +
'<strong>' + person.name + '</strong>' +
'<div>Github: <a href="https://github.com/' + person.github + '" target="_blank">' + person.github + '</a></div>' +
'<div>GitHub: <a href="https://github.com/' + person.github + '" target="_blank">' + person.github + '</a></div>' +
'<div>Twitter: <a href="https://twitter.com/' + person.twitter + '" target="_blank">' + person.twitter + '</a></div>' +
'</div>' +
'</li><br/>'
Expand Down
35 changes: 26 additions & 9 deletions index.d.ts
Expand Up @@ -21,8 +21,7 @@ type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean;

export class AxiosHeaders {
constructor(
headers?: RawAxiosHeaders | AxiosHeaders,
defaultHeaders?: RawAxiosHeaders | AxiosHeaders
headers?: RawAxiosHeaders | AxiosHeaders
);

set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
Expand All @@ -39,12 +38,16 @@ export class AxiosHeaders {

normalize(format: boolean): AxiosHeaders;

concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string>): AxiosHeaders;

toJSON(asStrings?: boolean): RawAxiosHeaders;

static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;

static accessor(header: string | string[]): AxiosHeaders;

static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string>): AxiosHeaders;

setContentType: AxiosHeaderSetter;
getContentType: AxiosHeaderGetter;
hasContentType: AxiosHeaderTester;
Expand Down Expand Up @@ -416,7 +419,7 @@ export interface AxiosInterceptorOptions {
}

export interface AxiosInterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number;
use(onFulfilled?: ((value: V) => V | Promise<V>) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions): number;
eject(id: number): void;
clear(): void;
}
Expand Down Expand Up @@ -463,19 +466,33 @@ export interface GenericHTMLFormElement {
submit(): void;
}

export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;

export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;

export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;

export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;

export function isCancel(value: any): value is Cancel;

export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;

export interface AxiosStatic extends AxiosInstance {
create(config?: CreateAxiosDefaults): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
AxiosError: typeof AxiosError;
readonly VERSION: string;
isCancel(value: any): value is Cancel;
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
isCancel: typeof isCancel;
all: typeof all;
spread: typeof spread;
isAxiosError: typeof isAxiosError;
toFormData: typeof toFormData;
formToJSON: typeof formToJSON;
CanceledError: typeof CanceledError;
AxiosHeaders: typeof AxiosHeaders;
}

declare const axios: AxiosStatic;
Expand Down
11 changes: 8 additions & 3 deletions index.js
@@ -1,5 +1,6 @@
import axios from './lib/axios.js';

// This module is intended to unwrap Axios default export as named.
// Keep top-level export same with static properties
// so that it can keep same with es module or cjs
const {
Expand All @@ -13,11 +14,13 @@ const {
Cancel,
isAxiosError,
spread,
toFormData
toFormData,
AxiosHeaders,
formToJSON
} = axios;

export default axios;
export {
axios as default,
Axios,
AxiosError,
CanceledError,
Expand All @@ -28,5 +31,7 @@ export {
Cancel,
isAxiosError,
spread,
toFormData
toFormData,
AxiosHeaders,
formToJSON
}
2 changes: 1 addition & 1 deletion karma.conf.cjs
Expand Up @@ -129,7 +129,7 @@ module.exports = function(config) {
);
browsers = ['Firefox'];
} else if (process.env.GITHUB_ACTIONS === 'true') {
console.log('Running ci on Github Actions.');
console.log('Running ci on GitHub Actions.');
browsers = ['FirefoxHeadless', 'ChromeHeadless'];
} else {
browsers = browsers || ['Chrome'];
Expand Down
4 changes: 2 additions & 2 deletions lib/adapters/http.js
Expand Up @@ -203,7 +203,7 @@ export default function httpAdapter(config) {
data: convertedData,
status: 200,
statusText: 'OK',
headers: {},
headers: new AxiosHeaders(),
config
});
}
Expand Down Expand Up @@ -588,4 +588,4 @@ export default function httpAdapter(config) {
});
}

export const __setProxy = setProxy;
export const __setProxy = setProxy;
8 changes: 5 additions & 3 deletions lib/axios.js
Expand Up @@ -14,6 +14,7 @@ import toFormData from './helpers/toFormData.js';
import AxiosError from './core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';
import AxiosHeaders from "./core/AxiosHeaders.js";

/**
* Create an instance of Axios
Expand Down Expand Up @@ -69,8 +70,9 @@ axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;

axios.formToJSON = thing => {
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
};
axios.AxiosHeaders = AxiosHeaders;

axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);

// this module should only have a default export
export default axios
18 changes: 10 additions & 8 deletions lib/core/Axios.js
Expand Up @@ -47,7 +47,7 @@ class Axios {

config = mergeConfig(this.defaults, config);

const {transitional, paramsSerializer} = config;
const {transitional, paramsSerializer, headers} = config;

if (transitional !== undefined) {
validator.assertOptions(transitional, {
Expand All @@ -67,20 +67,22 @@ class Axios {
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();

let contextHeaders;

// Flatten headers
const defaultHeaders = config.headers && utils.merge(
config.headers.common,
config.headers[config.method]
contextHeaders = headers && utils.merge(
headers.common,
headers[config.method]
);

defaultHeaders && utils.forEach(
contextHeaders && utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
(method) => {
delete headers[method];
}
);

config.headers = new AxiosHeaders(config.headers, defaultHeaders);
config.headers = AxiosHeaders.concat(contextHeaders, headers);

// filter out skipped interceptors
const requestInterceptorChain = [];
Expand Down