Skip to content

Commit

Permalink
docs: add example using proxy with fetch (nodejs#3800)
Browse files Browse the repository at this point in the history
* docs: add example using proxy with fetch

* remove main function and use TLA
  • Loading branch information
dancastillo authored and flakey5 committed Nov 14, 2024
1 parent 014e0cb commit f28e6b3
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions docs/examples/proxy/fetch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as http from 'node:http'
import { once } from 'node:events'
import { createProxy } from 'proxy'
import { ProxyAgent } from '../../../index.js'

const proxyServer = createProxy(http.createServer())
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('okay')
})

proxyServer.on('request', (req, res) => {
console.log(`Incoming request to ${req.url}`)
})

await once(proxyServer.listen(0), 'listening')
await once(server.listen(0), 'listening')

const { port: proxyPort } = proxyServer.address()
const { port } = server.address()

console.log(`Proxy listening on port ${proxyPort}`)
console.log(`Server listening on port ${port}`)
try {
// undici does a tunneling to the proxy server using CONNECT.
const agent = new ProxyAgent(`http://localhost:${proxyPort}`)
const response = await fetch(`http://localhost:${port}`, {
dispatcher: agent,
method: 'GET'
})
const data = await response.text()
console.log('Response data:', data)
} catch (e) {
console.log(e)
}

0 comments on commit f28e6b3

Please sign in to comment.