如何使用带有代理服务器的 axios 进行 https 调用?

Sw0*_*0ut 11 javascript axios

这里基本上是同样的问题

我正在使用浏览器。以下代码由 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.
Run Code Online (Sandbox Code Playgroud)

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

const axios = require('axios-https-proxy-fix');
Run Code Online (Sandbox Code Playgroud)

然后,我尝试使用 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.
Run Code Online (Sandbox Code Playgroud)

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

leo*_*pal 13

axios 的 github 页面上有一个未解决的问题。

该问题自 3 月 31 日起被标记为错误,尚未解决。

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

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

如果您等不及这个问题得到解决,您可以考虑使用评论中提出的@Sumi Straessle 之类的fetch API

  • 确实......我将在这里发布我所说的内容,但我刚刚使用 node-fetch 进行了测试,并且在 5 分钟内我已经能够完成使用 axios 在 2 天内无法成功完成的操作。我会坚持使用 node-fetch。感谢您的回答和您的时间。 (2认同)

ara*_*ddy 5

如果您想使用 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});
Run Code Online (Sandbox Code Playgroud)