forked from nodejs/undici
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
94 lines (80 loc) · 2.25 KB
/
request.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict'
const { request } = require('../../')
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)
}
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('node: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
}