【问题标题】:How to use authenticated proxies with undici如何在 undici 中使用经过身份验证的代理
【发布时间】:2021-03-03 15:10:49
【问题描述】:

您好,我正在尝试将 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 
},

但似乎没有任何效果

【问题讨论】:

    标签: javascript node.js proxy request


    【解决方案1】:

    在此处查看此链接: 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))
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多