Skip to content

Commit 30b2d91

Browse files
authored
Add request examples. (#2380)
* Add request examples. * fix DELETE example * ensure test covers error handling part of example
1 parent b942a70 commit 30b2d91

File tree

4 files changed

+239
-4
lines changed

4 files changed

+239
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ Returns a promise with the result of the `Dispatcher.request` method.
119119

120120
Calls `options.dispatcher.request(options)`.
121121

122-
See [Dispatcher.request](./docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details.
122+
See [Dispatcher.request](./docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details, and [request examples](./examples/README.md) for examples.
123123

124124
### `undici.stream([url, options, ]factory): Promise`
125125

examples/README.md

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
2+
## undici.request() examples
3+
4+
### A simple GET request, read the response body as text:
5+
```js
6+
const { request } = require('undici')
7+
async function getRequest (port = 3001) {
8+
// A simple GET request
9+
const {
10+
statusCode,
11+
headers,
12+
body
13+
} = await request(`http://localhost:${port}/`)
14+
15+
const data = await body.text()
16+
console.log('response received', statusCode)
17+
console.log('headers', headers)
18+
console.log('data', data)
19+
}
20+
```
21+
22+
### A JSON POST request, read the response body as json:
23+
```js
24+
const { request } = require('undici')
25+
async function postJSONRequest (port = 3001) {
26+
const requestBody = {
27+
hello: 'JSON POST Example body'
28+
}
29+
30+
const {
31+
statusCode,
32+
headers,
33+
body
34+
} = await request(
35+
`http://localhost:${port}/json`,
36+
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(requestBody) }
37+
)
38+
39+
// .json() will fail if we did not receive a valid json body in response:
40+
const decodedJson = await body.json()
41+
console.log('response received', statusCode)
42+
console.log('headers', headers)
43+
console.log('data', decodedJson)
44+
}
45+
```
46+
47+
### A Form POST request, read the response body as text:
48+
```js
49+
const { request } = require('undici')
50+
async function postFormRequest (port = 3001) {
51+
// Make a URL-encoded form POST request:
52+
const qs = require('querystring')
53+
54+
const requestBody = {
55+
hello: 'URL Encoded Example body'
56+
}
57+
58+
const {
59+
statusCode,
60+
headers,
61+
body
62+
} = await request(
63+
`http://localhost:${port}/form`,
64+
{ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify(requestBody) }
65+
)
66+
67+
const data = await body.text()
68+
console.log('response received', statusCode)
69+
console.log('headers', headers)
70+
console.log('data', data)
71+
}
72+
```
73+
74+
### A DELETE request
75+
```js
76+
const { request } = require('undici')
77+
async function deleteRequest (port = 3001) {
78+
// Make a DELETE request
79+
const {
80+
statusCode,
81+
headers,
82+
body
83+
} = await request(
84+
`http://localhost:${port}/something`,
85+
{ method: 'DELETE' }
86+
)
87+
88+
console.log('response received', statusCode)
89+
console.log('headers', headers)
90+
// For a DELETE request we expect a 204 response with no body if successful, in which case getting the body content with .json() will fail
91+
if (statusCode === 204) {
92+
console.log('delete successful')
93+
// always consume the body if there is one:
94+
await body.dump()
95+
} else {
96+
const data = await body.text()
97+
console.log('received unexpected data', data)
98+
}
99+
}
100+
```

examples/request.js

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,93 @@
22

33
const { request } = require('../')
44

5-
async function main () {
5+
async function getRequest (port = 3001) {
6+
// A simple GET request
67
const {
78
statusCode,
89
headers,
910
body
10-
} = await request('http://localhost:3001/')
11+
} = await request(`http://localhost:${port}/`)
1112

1213
const data = await body.text()
1314
console.log('response received', statusCode)
1415
console.log('headers', headers)
1516
console.log('data', data)
1617
}
1718

18-
main()
19+
async function postJSONRequest (port = 3001) {
20+
// Make a JSON POST request:
21+
22+
const requestBody = {
23+
hello: 'JSON POST Example body'
24+
}
25+
26+
const {
27+
statusCode,
28+
headers,
29+
body
30+
} = await request(
31+
`http://localhost:${port}/json`,
32+
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(requestBody) }
33+
)
34+
35+
// .json() will fail if we did not receive a valid json body in response:
36+
const decodedJson = await body.json()
37+
console.log('response received', statusCode)
38+
console.log('headers', headers)
39+
console.log('data', decodedJson)
40+
}
41+
42+
async function postFormRequest (port = 3001) {
43+
// Make a URL-encoded form POST request:
44+
const qs = require('querystring')
45+
46+
const requestBody = {
47+
hello: 'URL Encoded Example body'
48+
}
49+
50+
const {
51+
statusCode,
52+
headers,
53+
body
54+
} = await request(
55+
`http://localhost:${port}/form`,
56+
{ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify(requestBody) }
57+
)
58+
59+
const data = await body.text()
60+
console.log('response received', statusCode)
61+
console.log('headers', headers)
62+
console.log('data', data)
63+
}
64+
65+
async function deleteRequest (port = 3001) {
66+
// Make a DELETE request
67+
const {
68+
statusCode,
69+
headers,
70+
body
71+
} = await request(
72+
`http://localhost:${port}/something`,
73+
{ method: 'DELETE' }
74+
)
75+
76+
console.log('response received', statusCode)
77+
console.log('headers', headers)
78+
// For a DELETE request we expect a 204 response with no body if successful, in which case getting the body content with .json() will fail
79+
if (statusCode === 204) {
80+
console.log('delete successful')
81+
// always consume the body if there is one:
82+
await body.dump()
83+
} else {
84+
const data = await body.text()
85+
console.log('received unexpected data', data)
86+
}
87+
}
88+
89+
module.exports = {
90+
getRequest,
91+
postJSONRequest,
92+
postFormRequest,
93+
deleteRequest
94+
}

test/examples.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'use strict'
2+
3+
const { createServer } = require('http')
4+
const { test } = require('tap')
5+
const examples = require('../examples/request.js')
6+
7+
test('request examples', async (t) => {
8+
let lastReq
9+
const exampleServer = createServer((req, res) => {
10+
lastReq = req
11+
if (req.method === 'DELETE') {
12+
res.statusCode = 204
13+
return res.end()
14+
} else if (req.method === 'POST') {
15+
res.statusCode = 200
16+
if (req.url === '/json') {
17+
res.setHeader('content-type', 'application/json')
18+
res.end('{"hello":"JSON Response"}')
19+
} else {
20+
res.end('hello=form')
21+
}
22+
} else {
23+
res.statusCode = 200
24+
res.end('hello')
25+
}
26+
})
27+
28+
const errorServer = createServer((req, res) => {
29+
lastReq = req
30+
res.statusCode = 400
31+
res.setHeader('content-type', 'application/json')
32+
res.end('{"error":"an error"}')
33+
})
34+
35+
t.teardown(exampleServer.close.bind(exampleServer))
36+
t.teardown(errorServer.close.bind(errorServer))
37+
38+
await exampleServer.listen(0)
39+
await errorServer.listen(0)
40+
41+
await examples.getRequest(exampleServer.address().port)
42+
t.equal(lastReq.method, 'GET')
43+
44+
await examples.postJSONRequest(exampleServer.address().port)
45+
t.equal(lastReq.method, 'POST')
46+
t.equal(lastReq.headers['content-type'], 'application/json')
47+
48+
await examples.postFormRequest(exampleServer.address().port)
49+
t.equal(lastReq.method, 'POST')
50+
t.equal(lastReq.headers['content-type'], 'application/x-www-form-urlencoded')
51+
52+
await examples.deleteRequest(exampleServer.address().port)
53+
t.equal(lastReq.method, 'DELETE')
54+
55+
await examples.deleteRequest(errorServer.address().port)
56+
t.equal(lastReq.method, 'DELETE')
57+
58+
t.end()
59+
})

0 commit comments

Comments
 (0)