Skip to content

Commit

Permalink
Update v2.x branch to align with v1.x (#4751)
Browse files Browse the repository at this point in the history
* Fixing proxy beforeRedirect regression (#4708)

* Adding Canceler parameters config and request (#4711)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixed `toFormData` regression bug (unreleased) with Array-like objects serialization; (#4714)

Added `toURLEncodedForm` helper;
Added automatic payload serialization to `application/x-www-form-urlencoded` to have parity with `multipart/form-data`;
Added test of handling `application/x-www-form-urlencoded` body by express.js;
Updated README.md;
Added missed param in JSDoc;
Fixed hrefs in README.md;

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Allow webpack users to overwrite buildins (#4715)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixed `AxiosError` status code type; (#4717)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixed `AxiosError` stack capturing; (#4718)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* allow type definition for axios instance methods (#4224)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* add `string[]` to `AxiosRequestHeaders` type (#4322)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixing AxiosRequestHeaders typings (#4334)

Co-authored-by: Shakirov Kirill <ksshakirov@sberautotech.ru>
Co-authored-by: Jay <jasonsaayman@gmail.com>

* Added the ability for the `url-encoded-form` serializer to respect the `formSerializer` config; (#4721)

Added test for `formSerializer` config in context of `url-encoded-form` serializer;

* Updated eslint config; (#4722)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* fix: add isCancel type assert (#4293)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Added data URL support for node.js; (#4725)

* Added data URL support for node.js;
Added missed data URL protocol for the browser environment;
Optimized JSON parsing in the default response transformer;
Refactored project structure;
Added `cause` prop for AxiosError instance that refers to the original error if it was wrapped with `AxiosError.from` method;
Added fromDataURI helper;
Added test for handling data:url as an `arraybuffer|text|stream`;

* Added throwing of 405 HTTP error if the method is not GET;

* Fix/4263/maxbodylength defaults (#4731)

* test(http): add test case for default body length in follow-redirects

* fix(http): provide proper default body length to follow-redirects

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Adding types for progress event callbacks (#4675)

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixed bug #4727 : toFormData Blob issue on node>v17; (#4728)

* Fixed bug #4727;
Added node 18.x to the CI;
Added hotfix for `ERR_OSSL_EVP_UNSUPPORTED` issue with karma running on node >=17.x;
Added `cross-env` to allow running build and test scripts on Windows platforms;

* Added conditional setting of `--openssl-legacy-provider` option for node versions >=17.x;

* Refactored ssl-hotfix & test script;

* Fixed and refactored default max body length test due to ECONNRESET failure;

* Added test for converting the data uri to a Blob;
Fixed bug with parsing mime type for Blob;

Co-authored-by: Jay <jasonsaayman@gmail.com>

* URL params serializer; (#4734)

* Refactored BuildURL helper to use URLSearchParams serializer;

* Updated typings;
Added TS test;

* Added `axios.formToJSON` method; (#4735)

* Draft

* Added `formDataToJSON` helper;
Added `axios.formToJSON` method;
Added client tests;

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Bump grunt from 1.5.2 to 1.5.3 (#4743)

Bumps [grunt](https://github.com/gruntjs/grunt) from 1.5.2 to 1.5.3.
- [Release notes](https://github.com/gruntjs/grunt/releases)
- [Changelog](https://github.com/gruntjs/grunt/blob/main/CHANGELOG)
- [Commits](gruntjs/grunt@v1.5.2...v1.5.3)

---
updated-dependencies:
- dependency-name: grunt
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Updated README.md; (#4742)

Updated index.d.ts;

Co-authored-by: Jay <jasonsaayman@gmail.com>

* chore: removed Travis CI config file as we have moved to GitHub actions

* chore: updated actions to run on new version based branches

* Fix/4737/timeout error message for http (#4738)

* Fixing timeoutErrorMessage in http calls

When timeoutErrorMessage was set this did not change anything in the error message, with this change the error message will be the configured message

* Testing timeoutErrorMessage in http calls

When timeoutErrorMessage was set this did not change anything in the error message, with this change the error message will be the configured message

Co-authored-by: Jay <jasonsaayman@gmail.com>

* Fixing content-type header repeated (#4745)

Co-authored-by: Jay <jasonsaayman@gmail.com>

Co-authored-by: Maxime Bargiel <maxime.bargiel@gmail.com>
Co-authored-by: 毛呆 <aweikalee@163.com>
Co-authored-by: Dmitriy Mozgovoy <robotshara@gmail.com>
Co-authored-by: Tom Ceuppens <t-c@live.be>
Co-authored-by: Jelle Schutter <jelle@schutter.xyz>
Co-authored-by: Rraji Abdelbari <57002508+estarossa0@users.noreply.github.com>
Co-authored-by: Kirill Shakirov <kirill-shakirov@mail.ru>
Co-authored-by: Shakirov Kirill <ksshakirov@sberautotech.ru>
Co-authored-by: chenjigeng <178854407@qq.com>
Co-authored-by: Dimitris Halatsis <dimitris_ha@hotmail.com>
Co-authored-by: Johann Cooper <johanngcooper@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Victor Augusto <vdbernardes@gmail.com>
Co-authored-by: João Gabriel Quaresma <j.quaresmasantos_98@hotmail.com>
  • Loading branch information
15 people committed May 28, 2022
1 parent 13dd93f commit 0d01599
Show file tree
Hide file tree
Showing 38 changed files with 1,080 additions and 222 deletions.
12 changes: 5 additions & 7 deletions .eslintrc.js
Expand Up @@ -54,17 +54,17 @@ module.exports = {
/**
* Best practices
*/
'consistent-return': 2, // http://eslint.org/docs/rules/consistent-return
'consistent-return': 0, // http://eslint.org/docs/rules/consistent-return
'curly': [2, 'multi-line'], // http://eslint.org/docs/rules/curly
'default-case': 2, // http://eslint.org/docs/rules/default-case
'dot-notation': [2, { // http://eslint.org/docs/rules/dot-notation
'allowKeywords': true
}],
'eqeqeq': 2, // http://eslint.org/docs/rules/eqeqeq
'eqeqeq': [2, "smart"], // http://eslint.org/docs/rules/eqeqeq
'guard-for-in': 2, // http://eslint.org/docs/rules/guard-for-in
'no-caller': 2, // http://eslint.org/docs/rules/no-caller
'no-else-return': 2, // http://eslint.org/docs/rules/no-else-return
'no-eq-null': 2, // http://eslint.org/docs/rules/no-eq-null
'no-eq-null': 0, // http://eslint.org/docs/rules/no-eq-null
'no-eval': 2, // http://eslint.org/docs/rules/no-eval
'no-extend-native': 2, // http://eslint.org/docs/rules/no-extend-native
'no-extra-bind': 2, // http://eslint.org/docs/rules/no-extra-bind
Expand All @@ -80,7 +80,7 @@ module.exports = {
'no-new-wrappers': 2, // http://eslint.org/docs/rules/no-new-wrappers
'no-octal': 2, // http://eslint.org/docs/rules/no-octal
'no-octal-escape': 2, // http://eslint.org/docs/rules/no-octal-escape
'no-param-reassign': 2, // http://eslint.org/docs/rules/no-param-reassign
'no-param-reassign': 0, // http://eslint.org/docs/rules/no-param-reassign
'no-proto': 2, // http://eslint.org/docs/rules/no-proto
'no-redeclare': 2, // http://eslint.org/docs/rules/no-redeclare
'no-return-assign': 2, // http://eslint.org/docs/rules/no-return-assign
Expand Down Expand Up @@ -114,9 +114,7 @@ module.exports = {
}],
'comma-style': [2, 'last'], // http://eslint.org/docs/rules/comma-style
'eol-last': 2, // http://eslint.org/docs/rules/eol-last
'func-names': [
1, 'as-needed'
], // http://eslint.org/docs/rules/func-names
'func-names': 0, // http://eslint.org/docs/rules/func-names
'key-spacing': [2, { // http://eslint.org/docs/rules/key-spacing
'beforeColon': false,
'afterColon': true
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Expand Up @@ -2,17 +2,17 @@ name: ci

on:
push:
branches: [master, 'release/*', dev]
branches: [master, 'v1.x/*', 'v2.x/*']
pull_request:
branches: [master, 'release/*', dev]
branches: [master, 'v1.x/*', 'v2.x/*']

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [12.x, 14.x, 16.x]
node-version: [12.x, 14.x, 16.x, 18.x]

steps:
- uses: actions/checkout@v2
Expand Down
16 changes: 0 additions & 16 deletions .travis.yml

This file was deleted.

211 changes: 174 additions & 37 deletions README.md
Expand Up @@ -10,6 +10,7 @@
[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)
![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios)

Promise based HTTP client for the browser and node.js

Expand Down Expand Up @@ -39,12 +40,14 @@ Promise based HTTP client for the browser and node.js
- [AbortController](#abortcontroller)
- [CancelToken 👎](#canceltoken-deprecated)
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
- [Browser](#browser)
- [Node.js](#nodejs)
- [Query string](#query-string)
- [Form data](#form-data)
- [Automatic serialization](#-automatic-serialization)
- [Manual FormData passing](#manual-formdata-passing)
- [URLSearchParams](#urlsearchparams)
- [Query string](#query-string-older-browsers)
- [🆕 Automatic serialization](#-automatic-serialization-to-urlsearchparams)
- [Using multipart/form-data format](#using-multipartform-data-format)
- [FormData](#formdata)
- [🆕 Automatic serialization](#-automatic-serialization-to-formdata)
- [Files Posting](#files-posting)
- [HTML Form Posting](#html-form-posting-browser)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
Expand All @@ -61,6 +64,7 @@ Promise based HTTP client for the browser and node.js
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- 🆕 Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings
- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)

## Browser Support
Expand Down Expand Up @@ -336,10 +340,9 @@ These are the available config options for making requests. Only the `url` is re
ID: 12345
},

// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, https://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
// `paramsSerializer` is an optional config in charge of serializing `params`
paramsSerializer: {
indexes: null // array indexes format (null - no brackets, false - empty brackets, true - brackets with indexes)
},

// `data` is the data to be sent as the request body
Expand Down Expand Up @@ -509,6 +512,13 @@ These are the available config options for making requests. Only the `url` is re
env: {
// The FormData class to be used to automatically serialize the payload into a FormData object
FormData: window?.FormData || global?.FormData
},

formSerializer: {
visitor: (value, key, path, helpers)=> {}; // custom visitor funaction to serrialize form values
dots: boolean; // use dots instead of brackets format
metaTokens: boolean; // keep special endings like {} in parameter key
indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
}
}
```
Expand Down Expand Up @@ -814,7 +824,9 @@ cancel();
> During the transition period, you can use both cancellation APIs, even for the same request:
## Using application/x-www-form-urlencoded format
## Using `application/x-www-form-urlencoded` format
### 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).
Expand All @@ -824,7 +836,7 @@ params.append('extraparam', 'value');
axios.post('/foo', params);
```
### Older browsers
### Query string (Older browsers)
For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
Expand Down Expand Up @@ -863,9 +875,83 @@ You can also use the [`qs`](https://github.com/ljharb/qs) library.
> NOTE:
> 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.
#### Form data
### 🆕 Automatic serialization to URLSearchParams
Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
```
const data = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
};

await axios.postForm('https://postman-echo.com/post', data,
{headers: {'content-type': 'application/x-www-form-urlencoded'}}
);
```
The server will handle it as
```js
{
x: '1',
'arr[]': [ '1', '2', '3' ],
'arr2[0]': '1',
'arr2[1][0]': '2',
'arr2[2]': '3',
'arr3[]': [ '1', '2', '3' ],
'users[0][name]': 'Peter',
'users[0][surname]': 'griffin',
'users[1][name]': 'Thomas',
'users[1][surname]': 'Anderson'
}
````

If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically

```js
var app = express();
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/', function (req, res, next) {
// echo body as JSON
res.send(JSON.stringify(req.body));
});
server = app.listen(3000);
```

## Using `multipart/form-data` format

### FormData

To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.
Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.

```js
const formData = new FormData();
formData.append('foo', 'bar');
##### 🆕 Automatic serialization
axios.post('https://httpbin.org/post', formData);
```

In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:

```js
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form)
```

### 🆕 Automatic serialization to FormData

Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
header is set to `multipart/form-data`.
Expand Down Expand Up @@ -904,7 +990,7 @@ Axios FormData serializer supports some special endings to perform the following
- `[]` - unwrap the array-like object as separate fields with the same key
> NOTE:
> unwrap/expand operation will be used by default on array-like objects
> unwrap/expand operation will be used by default on arrays and FileList objects
FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
Expand Down Expand Up @@ -952,45 +1038,96 @@ formData.append('users[1][surname]', 'Anderson');
formData.append('obj2{}', '[{"x":1}]');
```
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.
## Files Posting
You can easily sumbit a single file
```js
const axios= require('axios');
await axios.postForm('https://httpbin.org/post', {
'myVar' : 'foo',
'file': document.querySelector('#fileInput').files[0]
});
```
axios.post('https://httpbin.org/post', {
'myObj{}': {x: 1, s: "foo"},
or multiple files as `multipart/form-data`.
```js
await axios.postForm('https://httpbin.org/post', {
'files[]': document.querySelector('#fileInput').files
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
});
```
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
which are just the corresponding http methods with the content-type header preset to `multipart/form-data`.
`FileList` object can be passed directly:
```js
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
```
All files will be sent with the same field names: `files[]`;
All files will be sent with the same field names: `files[]`.
##### Manual FormData passing
In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
## 🆕 HTML Form Posting (browser)
Pass HTML Form element as a payload to submit it as `multipart/form-data` content.
```js
const FormData = require('form-data');

const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
```
axios.post('https://example.com', form)
`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
```js
await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
headers: {
'Content-Type': 'application/json'
}
})
```
For example, the Form
```html
<form id="form">
<input type="text" name="foo" value="1">
<input type="text" name="deep.prop" value="2">
<input type="text" name="deep prop spaced" value="3">
<input type="text" name="baz" value="4">
<input type="text" name="baz" value="5">

<select name="user.age">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>

<input type="submit" value="Save">
</form>
```
will be submitted as the following JSON object:
```js
{
"foo": "1",
"deep": {
"prop": {
"spaced": "3"
}
},
"baz": [
"4",
"5"
],
"user": {
"age": "value2"
}
}
````

Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.

## Semver

Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
Expand Down

0 comments on commit 0d01599

Please sign in to comment.