Skip to content

Commit 9f73f91

Browse files
authored
docs: easy form (#88)
1 parent 4670944 commit 9f73f91

File tree

3 files changed

+39
-6
lines changed

3 files changed

+39
-6
lines changed

README.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,22 @@ try {
7272
}
7373
```
7474

75-
File uploads (multipart/form-data) can be achieved by using [form-data](https://github.com/form-data/form-data) package as shown below:
75+
File uploads (`multipart/form-data`) or form submit (`x-www-form-urlencoded`) can be achieved by using [form-auto-content](https://github.com/Eomm/form-auto-content) package as shown below:
7676

7777
```js
78-
const FormData = require('form-data')
78+
const formAutoContent = require('form-auto-content')
7979
const fs = require('fs')
8080

8181
try {
82-
const form = new FormData()
83-
form.append('myfile', fs.createReadStream(`./path/to/file`))
82+
const form = formAutoContent({
83+
myField: 'hello',
84+
myFile: fs.createReadStream(`./path/to/file`)
85+
})
8486

8587
const res = await inject(dispatch, {
8688
method: 'post',
8789
url: '/upload',
88-
payload: form,
89-
headers: form.getHeaders()
90+
...form
9091
})
9192
console.log(res.payload)
9293
} catch (err) {

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"types": "index.d.ts",
1313
"devDependencies": {
1414
"@types/node": "^13.1.0",
15+
"form-auto-content": "^1.0.0",
1516
"form-data": "^3.0.0",
1617
"pre-commit": "^1.2.2",
1718
"standard": "^14.0.2",

test/test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const inject = require('../index')
1212
const parseURL = require('../lib/parseURL')
1313

1414
const FormData = require('form-data')
15+
const formAutoContent = require('form-auto-content')
1516

1617
const httpMethods = [
1718
'delete',
@@ -1477,3 +1478,33 @@ test('errors for invalid undefined header value', (t) => {
14771478
t.ok(err)
14781479
}
14791480
})
1481+
1482+
test('example with form-auto-content', (t) => {
1483+
t.plan(4)
1484+
const dispatch = function (req, res) {
1485+
let body = ''
1486+
req.on('data', d => {
1487+
body += d
1488+
})
1489+
req.on('end', () => {
1490+
res.end(body)
1491+
})
1492+
}
1493+
1494+
const form = formAutoContent({
1495+
myField: 'my value',
1496+
myFile: fs.createReadStream('./LICENSE')
1497+
})
1498+
1499+
inject(dispatch, {
1500+
method: 'POST',
1501+
url: 'http://example.com:8080/hello',
1502+
payload: form.payload,
1503+
headers: form.headers
1504+
}, (err, res) => {
1505+
t.error(err)
1506+
t.equal(res.statusCode, 200)
1507+
t.ok(/--.+\r\nContent-Disposition: form-data; name="myField"\r\n\r\nmy value\r\n--.*/.test(res.payload))
1508+
t.ok(/--.+\r\nContent-Disposition: form-data; name="myFile"; filename="LICENSE"\r\n.*/.test(res.payload))
1509+
})
1510+
})

0 commit comments

Comments
 (0)