这基本上是同样的问题。
我正在使用浏览器。下面的代码是通过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.
这是一个错误吗?我是被诅咒了还是我在阅读文档时遇到了问题?
如果您想使用 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});
axios 的 github 页面有一个 open 问题。
尚未解决。
您可以将您的详细信息添加到该线程中,以便开发团队优先考虑此问题。
如果您等不及解决此问题,您可以考虑使用
fetch API,如评论中建议的@Sumi Straessle。
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。
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)
我在这篇文章中找到了此问题的解决方案:
https://janmolak.com/node-js-axios-behind-corporate-proxies-8b17a6f31f9d。现在完美运行了!