Skip to content

Commit fe1f132

Browse files
authored
docs: add example using proxy with fetch (#3800)
* docs: add example using proxy with fetch * remove main function and use TLA
1 parent 9288aad commit fe1f132

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/examples/proxy/fetch.mjs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import * as http from 'node:http'
2+
import { once } from 'node:events'
3+
import { createProxy } from 'proxy'
4+
import { ProxyAgent } from '../../../index.js'
5+
6+
const proxyServer = createProxy(http.createServer())
7+
const server = http.createServer((req, res) => {
8+
res.writeHead(200, { 'Content-Type': 'text/plain' })
9+
res.end('okay')
10+
})
11+
12+
proxyServer.on('request', (req, res) => {
13+
console.log(`Incoming request to ${req.url}`)
14+
})
15+
16+
await once(proxyServer.listen(0), 'listening')
17+
await once(server.listen(0), 'listening')
18+
19+
const { port: proxyPort } = proxyServer.address()
20+
const { port } = server.address()
21+
22+
console.log(`Proxy listening on port ${proxyPort}`)
23+
console.log(`Server listening on port ${port}`)
24+
try {
25+
// undici does a tunneling to the proxy server using CONNECT.
26+
const agent = new ProxyAgent(`http://localhost:${proxyPort}`)
27+
const response = await fetch(`http://localhost:${port}`, {
28+
dispatcher: agent,
29+
method: 'GET'
30+
})
31+
const data = await response.text()
32+
console.log('Response data:', data)
33+
} catch (e) {
34+
console.log(e)
35+
}

0 commit comments

Comments
 (0)