Skip to content

Commit

Permalink
docs: easy form (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
Eomm authored May 3, 2020
1 parent 4670944 commit 9f73f91
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,22 @@ try {
}
```

File uploads (multipart/form-data) can be achieved by using [form-data](https://github.com/form-data/form-data) package as shown below:
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:

```js
const FormData = require('form-data')
const formAutoContent = require('form-auto-content')
const fs = require('fs')

try {
const form = new FormData()
form.append('myfile', fs.createReadStream(`./path/to/file`))
const form = formAutoContent({
myField: 'hello',
myFile: fs.createReadStream(`./path/to/file`)
})

const res = await inject(dispatch, {
method: 'post',
url: '/upload',
payload: form,
headers: form.getHeaders()
...form
})
console.log(res.payload)
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"types": "index.d.ts",
"devDependencies": {
"@types/node": "^13.1.0",
"form-auto-content": "^1.0.0",
"form-data": "^3.0.0",
"pre-commit": "^1.2.2",
"standard": "^14.0.2",
Expand Down
31 changes: 31 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const inject = require('../index')
const parseURL = require('../lib/parseURL')

const FormData = require('form-data')
const formAutoContent = require('form-auto-content')

const httpMethods = [
'delete',
Expand Down Expand Up @@ -1477,3 +1478,33 @@ test('errors for invalid undefined header value', (t) => {
t.ok(err)
}
})

test('example with form-auto-content', (t) => {
t.plan(4)
const dispatch = function (req, res) {
let body = ''
req.on('data', d => {
body += d
})
req.on('end', () => {
res.end(body)
})
}

const form = formAutoContent({
myField: 'my value',
myFile: fs.createReadStream('./LICENSE')
})

inject(dispatch, {
method: 'POST',
url: 'http://example.com:8080/hello',
payload: form.payload,
headers: form.headers
}, (err, res) => {
t.error(err)
t.equal(res.statusCode, 200)
t.ok(/--.+\r\nContent-Disposition: form-data; name="myField"\r\n\r\nmy value\r\n--.*/.test(res.payload))
t.ok(/--.+\r\nContent-Disposition: form-data; name="myFile"; filename="LICENSE"\r\n.*/.test(res.payload))
})
})

0 comments on commit 9f73f91

Please sign in to comment.