Skip to content

Commit 9310060

Browse files
Added multipart topic; Updated url-encoded topic; (axios#77)
* [Updated] Added `multipart` topic; [Updated] `url-encoded` topic; [Added] http server script; * [Updated] Added docs; --------- Co-authored-by: Jay <[email protected]>
1 parent 3ad7e8f commit 9310060

7 files changed

+301
-31
lines changed

en.lang.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,12 @@ module.exports = {
103103
{
104104
type: "link",
105105
href: "/docs/urlencoded",
106-
text: "URL-Encoding Bodies",
106+
text: "🆕 URL-Encoding Bodies",
107+
},
108+
{
109+
type: "link",
110+
href: "/docs/multipart",
111+
text: "🆕 Multipart Bodies",
107112
},
108113
{
109114
type: "heading",

package.json

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
"name": "axios-docs",
33
"version": "0.4.0",
44
"scripts": {
5-
"build": "inert build"
5+
"build": "inert build",
6+
"server": "http-server ./public/"
67
},
78
"description": "The official axios documentation website",
89
"repository": "https://github.com/axios/axios-docs.git",
910
"author": "codemaster138 <[email protected]>",
1011
"license": "MIT",
1112
"devDependencies": {
12-
"inert-ssg": "^2.0.0-alpha.15"
13+
"inert-ssg": "^2.0.0-alpha.15",
14+
"http-server": "^14.1.0"
1315
}
1416
}

posts/en/api_intro.md

+3
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ For convenience aliases have been provided for all supported request methods.
5454
##### axios.post(url[, data[, config]])
5555
##### axios.put(url[, data[, config]])
5656
##### axios.patch(url[, data[, config]])
57+
##### axios.postForm(url[, data[, config]])
58+
##### axios.putForm(url[, data[, config]])
59+
##### axios.patchForm(url[, data[, config]])
5760

5861
###### NOTE
5962
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.

posts/en/intro.md

+19-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,17 @@ Axios is a *[promise-based](https://javascript.info/promise-basics)* HTTP Client
1616
- Intercept request and response
1717
- Transform request and response data
1818
- Cancel requests
19-
- Automatic transforms for JSON data
19+
- Timeouts
20+
- Query parameters serialization with support for nested entries
21+
- Automatic request body serialization to:
22+
- JSON (`application/json`)
23+
- Multipart / FormData (`multipart/form-data`)
24+
- URL encoded form (`application/x-www-form-urlencoded`)
25+
- Posting HTML forms as JSON
26+
- Automatic JSON data handling in response
27+
- Progress capturing for browsers and node.js with extra info (speed rate, remaining time)
28+
- Setting bandwidth limits for node.js
29+
- Compatible with spec-compliant FormData and Blob (including `node.js`)
2030
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
2131

2232
# Installing
@@ -49,4 +59,11 @@ Using unpkg CDN:
4959

5060
```html
5161
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
52-
```
62+
```
63+
64+
Prebuilt CommonJS modules for direct importing with require (if your module bundler failed to resolve them automatically)
65+
66+
```js
67+
const axios = require('axios/dist/browser/axios.cjs'); // browser
68+
const axios = require('axios/dist/node/axios.cjs'); // node
69+
```

posts/en/multipart.md

+170
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
---
2+
title: 'Multipart Bodies'
3+
prev_title: 'URL-Encoding Bodies'
4+
prev_link: '/docs/urlencoded'
5+
next_title: 'Notes'
6+
next_link: '/docs/notes'
7+
---
8+
9+
## Posting data as `multipart/form-data`
10+
11+
### Using FormData API
12+
13+
#### Browser
14+
15+
```js
16+
const form = new FormData();
17+
form.append('my_field', 'my value');
18+
form.append('my_buffer', new Blob([1,2,3]));
19+
form.append('my_file', fileInput.files[0]);
20+
21+
axios.post('https://example.com', form)
22+
```
23+
24+
The same result can be achieved using the internal Axios serializer and corresponding shorthand method:
25+
26+
```js
27+
axios.postForm('https://httpbin.org/post', {
28+
my_field: 'my value',
29+
my_buffer: new Blob([1,2,3]),
30+
my_file: fileInput.files // FileList will be unwrapped as sepate fields
31+
});
32+
```
33+
34+
HTML form can be passes directly as a request payload
35+
36+
#### Node.js
37+
38+
```js
39+
import axios from 'axios';
40+
41+
const form = new FormData();
42+
form.append('my_field', 'my value');
43+
form.append('my_buffer', new Blob(['some content']));
44+
45+
axios.post('https://example.com', form)
46+
```
47+
48+
Since node.js does not currently support creating a `Blob` from a file, you can use a third-party package for this purpose.
49+
50+
```js
51+
import {fileFromPath} from 'formdata-node/file-from-path'
52+
53+
form.append('my_field', 'my value');
54+
form.append('my_file', await fileFromPath('/foo/bar.jpg'));
55+
56+
axios.post('https://example.com', form)
57+
```
58+
59+
For Axios older than `v1.3.0` you must import `form-data` package.
60+
61+
```js
62+
const FormData = require('form-data');
63+
64+
const form = new FormData();
65+
form.append('my_field', 'my value');
66+
form.append('my_buffer', new Buffer(10));
67+
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
68+
69+
axios.post('https://example.com', form)
70+
```
71+
72+
### 🆕 Automatic serialization
73+
74+
Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData
75+
object if the request Content-Type header is set to `multipart/form-data`.
76+
77+
The following request will submit the data in a FormData format (Browser & Node.js):
78+
79+
```js
80+
import axios from 'axios';
81+
82+
axios.post('https://httpbin.org/post', {
83+
user: {
84+
name: 'Dmitriy'
85+
},
86+
file: fs.createReadStream('/foo/bar.jpg')
87+
}, {
88+
headers: {
89+
'Content-Type': 'multipart/form-data'
90+
}
91+
}).then(({data})=> console.log(data));
92+
```
93+
94+
Axios FormData serializer supports some special endings to perform the following operations:
95+
96+
- `{}` - serialize the value with JSON.stringify
97+
- `[]` - unwrap the array-like object as separate fields with the same key
98+
99+
> NOTE:
100+
> unwrap/expand operation will be used by default on arrays and FileList objects
101+
102+
FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
103+
104+
- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object
105+
to a `FormData` object by following custom rules.
106+
107+
- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
108+
109+
- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
110+
The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
111+
112+
- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects
113+
114+
- `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
115+
- `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
116+
- `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
117+
118+
Let's say we have an object like this one:
119+
120+
```js
121+
const obj = {
122+
x: 1,
123+
arr: [1, 2, 3],
124+
arr2: [1, [2], 3],
125+
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
126+
'obj2{}': [{x:1}]
127+
};
128+
```
129+
130+
The following steps will be executed by the Axios serializer internally:
131+
132+
```js
133+
const formData= new FormData();
134+
formData.append('x', '1');
135+
formData.append('arr[]', '1');
136+
formData.append('arr[]', '2');
137+
formData.append('arr[]', '3');
138+
formData.append('arr2[0]', '1');
139+
formData.append('arr2[1][0]', '2');
140+
formData.append('arr2[2]', '3');
141+
formData.append('users[0][name]', 'Peter');
142+
formData.append('users[0][surname]', 'Griffin');
143+
formData.append('users[1][name]', 'Thomas');
144+
formData.append('users[1][surname]', 'Anderson');
145+
formData.append('obj2{}', '[{"x":1}]');
146+
```
147+
148+
```js
149+
import axios from 'axios';
150+
151+
axios.post('https://httpbin.org/post', {
152+
'myObj{}': {x: 1, s: "foo"},
153+
'files[]': document.querySelector('#fileInput').files
154+
}, {
155+
headers: {
156+
'Content-Type': 'multipart/form-data'
157+
}
158+
}).then(({data})=> console.log(data));
159+
```
160+
161+
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
162+
which are just the corresponding http methods with the content-type header preset to `multipart/form-data`.
163+
164+
`FileList` object can be passed directly:
165+
166+
```js
167+
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
168+
```
169+
170+
All files will be sent with the same field names: `files[]`;

posts/en/post_example.md

+51-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ next_title: 'Axios API'
77
next_link: '/docs/api_intro'
88
---
99

10-
Performing a `POST` request
10+
## Performing a `POST` request
11+
12+
### JSON
1113

1214
```js
1315
axios.post('/user', {
@@ -33,9 +35,54 @@ function getUserPermissions() {
3335
return axios.get('/user/12345/permissions');
3436
}
3537

38+
const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);
39+
40+
// OR
41+
3642
Promise.all([getUserAccount(), getUserPermissions()])
37-
.then(function (results) {
38-
const acct = results[0];
39-
const perm = results[1];
43+
.then(function ([acct, perm]) {
44+
// ...
4045
});
4146
```
47+
48+
Post an HTML form as JSON
49+
50+
```js
51+
const {data} = await axios.post('/user', document.querySelector('#my-form'), {
52+
headers: {
53+
'Content-Type': 'application/json'
54+
}
55+
})
56+
```
57+
58+
### Forms
59+
60+
- Multipart (`multipart/form-data`)
61+
62+
```js
63+
const {data} = await axios.post('https://httpbin.org/post', {
64+
firstName: 'Fred',
65+
lastName: 'Flintstone',
66+
orders: [1, 2, 3],
67+
photo: document.querySelector('#fileInput').files
68+
}, {
69+
headers: {
70+
'Content-Type': 'multipart/form-data'
71+
}
72+
}
73+
)
74+
```
75+
76+
- URL encoded form (`application/x-www-form-urlencoded`)
77+
78+
```js
79+
const {data} = await axios.post('https://httpbin.org/post', {
80+
firstName: 'Fred',
81+
lastName: 'Flintstone',
82+
orders: [1, 2, 3]
83+
}, {
84+
headers: {
85+
'Content-Type': 'application/x-www-form-urlencoded'
86+
}
87+
})
88+
```

0 commit comments

Comments
 (0)