Skip to content

Commit

Permalink
Add request examples. (nodejs#2380)
Browse files Browse the repository at this point in the history
* Add request examples.

* fix DELETE example

* ensure test covers error handling part of example
  • Loading branch information
autopulated authored and crysmags committed Feb 27, 2024
1 parent 44cffbe commit 83c1dd7
Show file tree
Hide file tree
Showing 4 changed files with 239 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ Returns a promise with the result of the `Dispatcher.request` method.

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

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

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

Expand Down
100 changes: 100 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@

## undici.request() examples

### A simple GET request, read the response body as text:
```js
const { request } = require('undici')
async function getRequest (port = 3001) {
// A simple GET request
const {
statusCode,
headers,
body
} = await request(`http://localhost:${port}/`)

const data = await body.text()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', data)
}
```

### A JSON POST request, read the response body as json:
```js
const { request } = require('undici')
async function postJSONRequest (port = 3001) {
const requestBody = {
hello: 'JSON POST Example body'
}

const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/json`,
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(requestBody) }
)

// .json() will fail if we did not receive a valid json body in response:
const decodedJson = await body.json()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', decodedJson)
}
```

### A Form POST request, read the response body as text:
```js
const { request } = require('undici')
async function postFormRequest (port = 3001) {
// Make a URL-encoded form POST request:
const qs = require('querystring')

const requestBody = {
hello: 'URL Encoded Example body'
}

const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/form`,
{ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify(requestBody) }
)

const data = await body.text()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', data)
}
```

### A DELETE request
```js
const { request } = require('undici')
async function deleteRequest (port = 3001) {
// Make a DELETE request
const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/something`,
{ method: 'DELETE' }
)

console.log('response received', statusCode)
console.log('headers', headers)
// 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
if (statusCode === 204) {
console.log('delete successful')
// always consume the body if there is one:
await body.dump()
} else {
const data = await body.text()
console.log('received unexpected data', data)
}
}
```
82 changes: 79 additions & 3 deletions examples/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,93 @@

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

async function main () {
async function getRequest (port = 3001) {
// A simple GET request
const {
statusCode,
headers,
body
} = await request('http://localhost:3001/')
} = await request(`http://localhost:${port}/`)

const data = await body.text()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', data)
}

main()
async function postJSONRequest (port = 3001) {
// Make a JSON POST request:

const requestBody = {
hello: 'JSON POST Example body'
}

const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/json`,
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(requestBody) }
)

// .json() will fail if we did not receive a valid json body in response:
const decodedJson = await body.json()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', decodedJson)
}

async function postFormRequest (port = 3001) {
// Make a URL-encoded form POST request:
const qs = require('querystring')

const requestBody = {
hello: 'URL Encoded Example body'
}

const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/form`,
{ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify(requestBody) }
)

const data = await body.text()
console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', data)
}

async function deleteRequest (port = 3001) {
// Make a DELETE request
const {
statusCode,
headers,
body
} = await request(
`http://localhost:${port}/something`,
{ method: 'DELETE' }
)

console.log('response received', statusCode)
console.log('headers', headers)
// 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
if (statusCode === 204) {
console.log('delete successful')
// always consume the body if there is one:
await body.dump()
} else {
const data = await body.text()
console.log('received unexpected data', data)
}
}

module.exports = {
getRequest,
postJSONRequest,
postFormRequest,
deleteRequest
}
59 changes: 59 additions & 0 deletions test/examples.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use strict'

const { createServer } = require('http')
const { test } = require('tap')
const examples = require('../examples/request.js')

test('request examples', async (t) => {
let lastReq
const exampleServer = createServer((req, res) => {
lastReq = req
if (req.method === 'DELETE') {
res.statusCode = 204
return res.end()
} else if (req.method === 'POST') {
res.statusCode = 200
if (req.url === '/json') {
res.setHeader('content-type', 'application/json')
res.end('{"hello":"JSON Response"}')
} else {
res.end('hello=form')
}
} else {
res.statusCode = 200
res.end('hello')
}
})

const errorServer = createServer((req, res) => {
lastReq = req
res.statusCode = 400
res.setHeader('content-type', 'application/json')
res.end('{"error":"an error"}')
})

t.teardown(exampleServer.close.bind(exampleServer))
t.teardown(errorServer.close.bind(errorServer))

await exampleServer.listen(0)
await errorServer.listen(0)

await examples.getRequest(exampleServer.address().port)
t.equal(lastReq.method, 'GET')

await examples.postJSONRequest(exampleServer.address().port)
t.equal(lastReq.method, 'POST')
t.equal(lastReq.headers['content-type'], 'application/json')

await examples.postFormRequest(exampleServer.address().port)
t.equal(lastReq.method, 'POST')
t.equal(lastReq.headers['content-type'], 'application/x-www-form-urlencoded')

await examples.deleteRequest(exampleServer.address().port)
t.equal(lastReq.method, 'DELETE')

await examples.deleteRequest(errorServer.address().port)
t.equal(lastReq.method, 'DELETE')

t.end()
})

0 comments on commit 83c1dd7

Please sign in to comment.