NodeJS 如何通过undici使用经过身份验证的代理

wyyhbhjk  于 2023-05-28  发布在  Node.js
关注(0)|答案(2)|浏览(152)

你好,所以我试图使用undici与代理,但它不工作,我累了这个

const client = new Client({
  url: 'www.google.com',
  proxy: 'http://user:pass@host:port'
})

还有这个

const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent("http://user:pass@host:port");
time = new Date()
client.request({
  path: '/',
  method: 'GET',
  httpsAgent: proxy 
},

但似乎都不管用

wrrgggsh

wrrgggsh1#

下面是我的工作实现:

import { Dispatcher, fetch, ProxyAgent } from 'undici';

const proxyAgent = new ProxyAgent({
      uri: `http://${your_proxy_ip}:${your_proxy_port}`,
      token: `Basic ${Buffer.from(`${your_proxy_username}:${your_proxy_password}`).toString('base64')}`,
    });

fetch(your_url, {dispatcher: proxyAgent})
vlf7wbxs

vlf7wbxs2#

在这里看到这个链接:https://github.com/nodejs/undici/blob/01302e6d2b2629cca4ad9327abe0f7a317f8399f/docs/best-practices/proxy.md#connect-with-authentication

import { Client } from 'undici'
import { createServer } from 'http'
import proxy from 'proxy'

const server = await buildServer()
const proxy = await buildProxy()

const serverUrl = `http://localhost:${server.address().port}`
const proxyUrl = `http://localhost:${proxy.address().port}`

proxy.authenticate = function (req, fn) {
  fn(null, req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`)
}

server.on('request', (req, res) => {
  console.log(req.url) // '/hello?foo=bar'
  res.setHeader('content-type', 'application/json')
  res.end(JSON.stringify({ hello: 'world' }))
})

const client = new Client(proxyUrl)

const response = await client.request({
  method: 'GET',
  path: serverUrl + '/hello?foo=bar',
  headers: {
    'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}`
  }
})

response.body.setEncoding('utf8')
let data = ''
for await (const chunk of response.body) {
  data += chunk
}
console.log(response.statusCode) // 200
console.log(JSON.parse(data)) // { hello: 'world' }

server.close()
proxy.close()
client.close()

function buildServer () {
  return new Promise((resolve, reject) => {
    const server = createServer()
    server.listen(0, () => resolve(server))
  })
}

function buildProxy () {
  return new Promise((resolve, reject) => {
    const server = proxy(createServer())
    server.listen(0, () => resolve(server))
  })
}

相关问题