Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add example using proxy with fetch #3800

Merged
merged 2 commits into from
Nov 7, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/examples/proxy/fetch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
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}`)
})

const main = async () => {
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)
}
}

main()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove the main function and use TLA

Loading