10000 Fixed merge conflicts · darth-coder-js/axios@8699891 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8699891

Browse files
committed
Fixed merge conflicts
2 parents c855c9d + 6b9b05b commit 8699891

File tree

22 files changed

+643
-160
lines changed

22 files changed

+643
-160
lines changed

README.md

Lines changed: 100 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Promise based HTTP client for the browser and node.js
2323
- [Example](#example)
2424
- [Axios API](#axios-api)
2525
- [Request method aliases](#request-method-aliases)
26-
- [Concurrency (Deprecated)](#concurrency-deprecated)
26+
- [Concurrency 👎](#concurrency-deprecated)
2727
- [Creating an instance](#creating-an-instance)
2828
- [Instance methods](#instance-methods)
2929
- [Request Config](#request-config)
@@ -36,11 +36,15 @@ Promise based HTTP client for the browser and node.js
3636
- [Multiple Interceptors](#multiple-interceptors)
3737
- [Handling Errors](#handling-errors)
3838
- [Cancellation](#cancellation)
39+
- [AbortController](#abortcontroller)
40+
- [CancelToken 👎](#canceltoken-deprecated)
3941
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
4042
- [Browser](#browser)
4143
- [Node.js](#nodejs)
4244
- [Query string](#query-string)
4345
- [Form data](#form-data)
46+
- [Automatic serialization](#-automatic-serialization)
47+
- [Manual FormData passing](#manual-formdata-passing)
4448
- [Semver](#semver)
4549
- [Promises](#promises)
4650
- [TypeScript](#typescript)
@@ -494,6 +498,11 @@ These are the available config options for making requests. Only the `url` is re
494498

495499
// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
496500
clarifyTimeoutError: false,
501+
},
502+
503+
env: {
504+
// The FormData class to be used to automatically serialize the payload into a FormData object
505+
FormData: window?.FormData || global?.FormData
497506
}
498507
}
499508
```
@@ -718,10 +727,30 @@ axios.get('/user/12345')
718727
719728
## Cancellation
720729
721-
You can cancel a request using a *cancel token*.
730+
### AbortController
731+
< F438 /div>
732+
Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
733+
734+
```js
735+
const controller = new AbortController();
736+
737+
axios.get('/foo/bar', {
738+
signal: controller.signal
739+
}).then(function(response) {
740+
//...
741+
});
742+
// cancel the request
743+
controller.abort()
744+
```
745+
746+
### CancelToken `👎deprecated`
747+
748+
You can also cancel a request using a *CancelToken*.
722749
723750
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
724751
752+
> This API is deprecated since v0.22.0 and shouldn't be used in new projects
753+
725754
You can create a cancel token using the `CancelToken.source` factory as shown below:
726755
727756
```js
@@ -765,22 +794,11 @@ axios.get('/user/12345', {
765794
cancel();
766795
```
767796
768-
Axios supports AbortController to abort requests in [`fetch API`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#aborting_a_fetch) way:
769-
```js
770-
const controller = new AbortController();
771-
772-
axios.get('/foo/bar', {
773-
signal: controller.signal
774-
}).then(function(response) {
775-
//...
776-
});
777-
// cancel the request
778-
controller.abort()
779-
```
780-
781797
> Note: you can cancel several requests with the same cancel token/abort controller.
782798
> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request.
783799
800+
> During the transition period, you can use both cancellation APIs, even for the same request:
801+
784802
## Using application/x-www-form-urlencoded format
785803
786804
By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
@@ -840,11 +858,75 @@ axios.post('http://something.com/', params.toString());
840858
841859
You can also use the [`qs`](https://github.com/ljharb/qs) library.
842860
843-
###### NOTE
844-
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
861+
> NOTE:
862+
> The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case.
845863
846864
#### Form data
847865
866+
##### 🆕 Automatic serialization
867+
868+
Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
869+
header is set to `multipart/form-data`.
870+
871+
The following request will submit the data in a FormData format (Browser & Node.js):
872+
873+
```js
874+
import axios from 'axios';
875+
876+
axios.post('https://httpbin.org/post', {x: 1}, {
877+
headers: {
878+
'Content-Type': 'multipart/form-data'
879+
}
880+
}).then(({data})=> console.log(data));
881+
```
882+
883+
In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
884+
885+
You can overload the FormData class by setting the `env.FormData` config variable,
886+
but you probably won't need it in most cases:
887+
888+
```js
889+
const axios= require('axios');
890+
var FormData = require('form-data');
891+
892+
axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
893+
headers: {
894+
'Content-Type': 'multipart/form-data'
895+
}
896+
}).then(({data})=> console.log(data));
897+
```
898+
899+
Axios FormData serializer supports some special endings to perform the following operations:
900+
901+
- `{}` - serialize the value with JSON.stringify
902+
- `[]` - unwrap the array like object as separate fields with the same key
903+
904+
```js
905+
const axios= require('axios');
906+
907+
axios.post('https://httpbin.org/post', {
908+
'myObj{}': {x: 1, s: "foo"},
909+
'files[]': document.querySelector('#fileInput').files
910+
}, {
911+
headers: {
912+
'Content-Type': 'multipart/form-data'
913+
}
914+
}).then(({data})=> console.log(data));
915+
```
916+
917+
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
918+
which are just the corresponding http methods with a header preset: `Content-Type`: `multipart/form-data`.
919+
920+
FileList object can be passed directly:
921+
922+
```js
923+
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
924+
```
925+
926+
All files will be sent with the same field names: `files[]`;
927+
928+
##### Manual FormData passing
929+
848930
In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
849931
850932
```js
@@ -855,18 +937,7 @@ form.append('my_field', 'my value');
855937
form.append('my_buffer', new Buffer(10));
856938
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
857939

858-
axios.post('https://example.com', form.getBuffer(), { headers: form.getHeaders() })
859-
```
860-
861-
Alternatively, use an interceptor:
862-
863-
```js
864-
axios.interceptors.request.use(config => {
865-
if (config.data instanceof FormData) {
866-
Object.assign(config.headers, config.data.getHeaders());
867-
}
868-
return config;
869-
});
940+
axios.post('https://example.com', form)
870941
```
871942
872943
## Semver

index.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ export interface AxiosRequestConfig<D = any> {
107107
transitional?: TransitionalOptions;
108108
signal?: AbortSignal;
109109
insecureHTTPParser?: boolean;
110+
env?: {
111+
FormData?: new (...args: any[]) => object;
112+
};
110113
}
111114

112115
export interface HeadersDefaults {
@@ -224,6 +227,9 @@ export class Axios {
224227
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
225228
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
226229
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
230+
postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
231+
putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
232+
patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
227233
}
228234

229235
export interface AxiosInstance extends Axios {

lib/adapters/http.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,10 @@ module.exports = function httpAdapter(config) {
8686
headers['User-Agent'] = 'axios/' + VERSION;
8787
}
8888

89-
if (data && !utils.isStream(data)) {
89+
// support for https://www.npmjs.com/package/form-data api
90+
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
91+
Object.assign(headers, data.getHeaders());
92+
} else if (data && !utils.isStream(data)) {
9093
if (Buffer.isBuffer(data)) {
9194
// Nothing to do...
9295
} else if (utils.isArrayBuffer(data)) {

lib/axios.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ axios.CanceledError = require('./cancel/CanceledError');
4141
axios.CancelToken = require('./cancel/CancelToken');
4242
axios.isCancel = require('./cancel/isCancel');
4343
axios.VERSION = require('./env/data').version;
44+
axios.toFormData = require('./helpers/toFormData');
4445

4546
// Expose AxiosError class
4647
axios.AxiosError = require('../lib/core/AxiosError');

lib/core/Axios.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -138,13 +138,23 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData
138138

139139
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
140140
/*eslint func-names:0*/
141-
Axios.prototype[method] = function(url, data, config) {
142-
return this.request(mergeConfig(config || {}, {
143-
method: method,
144-
url: url,
145-
data: data
146-
}));
147-
};
141+
142+
function generateHTTPMethod(isForm) {
143+
return function httpMethod(url, data, config) {
144+
return this.request(mergeConfig(config || {}, {
145+
method: method,
146+
headers: isForm ? {
147+
'Content-Type': 'multipart/form-data'
148+
} : {},
149+
url: url,
150+
data: data
151+
}));
152+
};
153+
}
154+
155+
Axios.prototype[method] = generateHTTPMethod();
156+
157+
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
148158
});
149159

150160
module.exports = Axios;

lib/defaults/env/FormData.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// eslint-disable-next-line strict
2+
module.exports = require('form-data');

lib/defaults/index.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ var utils = require('../utils');
44
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
55
var AxiosError = require('../core/AxiosError');
66
var transitionalDefaults = require('./transitional');
7+
var toFormData = require('./helpers/toFormData');
78

89
var DEFAULT_CONTENT_TYPE = {
910
'Content-Type': 'application/x-www-form-urlencoded'
@@ -68,10 +69,20 @@ var defaults = {
6869
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
6970
return data.toString();
7071
}
71-
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
72+
73+
var isObjectPayload = utils.isObject(data);
74+
var contentType = headers && headers['Content-Type'];
75+
76+
var isFileList;
77+
78+
if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
79+
var _FormData = this.env && this.env.FormData;
80+
return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
81+
} else if (isObjectPayload || contentType === 'application/json') {
7282
setContentTypeIfUnset(headers, 'application/json');
7383
return stringifySafely(data);
7484
}
85+
7586
return data;
7687
}],
7788

@@ -109,6 +120,10 @@ var defaults = {
109120
maxContentLength: -1,
110121
maxBodyLength: -1,
111122

123+
env: {
124+
FormData: require('./defaults/env/FormData')
125+
},
126+
112127
validateStatus: function validateStatus(status) {
113128
return status >= 200 && status < 300;
114129
},

lib/helpers/null.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// eslint-disable-next-line strict
2+
module.exports = null;

0 commit comments

Comments
 (0)
0