如何使用axios配合代理服务器进行https调用?

问题描述 投票:0回答:6

这基本上是同样的问题

我正在使用浏览器。下面的代码是通过webpack编译的。 我试过这个:

const axios = require('axios');

var res = await axios.get('https://api.ipify.org?format=json', {
    proxy: {
        host: 'proxy-url',
        port: 80,
        auth: {username: 'my-user', password: 'my-password'}
    }
});
console.log(res.data); // gives my ip and not the proxy's one.

我也用相同的代码尝试过这个,但它不起作用:

const axios = require('axios-https-proxy-fix');

然后,我尝试使用 httpsAgent:

const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent')

var agent = new HttpsProxyAgent('http://my-user:my-pass@proxy-url:port');
var res = await axios.get('https://api.ipify.org?format=json', {
    httpsAgent: agent,
});
console.log(res.data); // gives my ip and not the proxy's one.

这是一个错误吗?我是被诅咒了还是我在阅读文档时遇到了问题?

javascript axios
6个回答
25
投票

如果您想使用 axios 并解决该问题,请考虑使用 https-proxy-agent 作为代理,如链接

中所述
    const HttpsProxyAgent = require("https-proxy-agent"),
      axios = require("axios");

const httpsAgent = new HttpsProxyAgent({host: "proxyhost", port: "proxyport", auth: "username:password"})

//use axios as you normally would, but specify httpsAgent in the config
axios = axios.create({httpsAgent});

20
投票

axios 的 github 页面有一个 open 问题。

该问题自 3 月 31 日起被标记为错误,并且

尚未解决

看来你没有被诅咒,只是 axios 中的一个错误。

您可以将您的详细信息添加到该线程中,以便开发团队优先考虑此问题。

如果您等不及解决此问题,您可以考虑使用

fetch API,如评论中建议的@Sumi Straessle。


4
投票
axios 的

config.proxy

 仅适用于 Node.js。我认为这在浏览器中毫无意义。

你可以检查

lib/adapters/xhr.js,会发现那里没有任何与代理相关的内容。


0
投票
我能够通过这样做让它工作

const agent = new HttpsProxyAgent(`http://proxy:port@username:password`); axios({ method: 'get', httpsAgent: agent, url: 'https://api.ipify.org?format=json' }).then(response => console.log(response.data)).catch(err => console.log(err))
我的代理是 

https,因此在定义 HttpsProxyAgent 时,请确保在 https 上使用 http


0
投票
这工作正常。主要问题是 HttpsProxyAgent import 语句。你可以尝试一下-

const axios = require('axios'); const {HttpsProxyAgent} = require('https-proxy-agent'); const proxyUrl = 'http://my-user:my-pass@proxy-url:port'; const agent = new HttpsProxyAgent(proxyUrl); const url = "https://www.google.com" // for example const response = await axios.get(url, {httpsAgent: agent}) console.log(response.data)
    

-4
投票
如果您尝试通过 HTTP 代理访问 HTTPS URL,则需要创建 HTTPS-HTTP 隧道。

我在这篇文章中找到了此问题的解决方案:

https://janmolak.com/node-js-axios-behind-corporate-proxies-8b17a6f31f9d。现在完美运行了!

© www.soinside.com 2019 - 2024. All rights reserved.