繁体   English   中英

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

[英]How to use axios with a proxy server to make an https call?

这里基本上是同样的问题

我正在使用浏览器。 以下代码由 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 的 github 页面上有一个未解决的问题。

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

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

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

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

如果您想使用 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 的config.proxy只是 Node.js。 我认为它在浏览器中毫无意义。

您可以检查lib/adapters/xhr.js并且在那里找不到与代理相关的任何内容。

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

我在这篇文章中找到了这个问题的解决方案: https : //janmolak.com/node-js-axios-behind-corporate-proxies-8b17a6f31f9d 现在它完美运行!

如果您使用的是 MERN 堆栈应用程序,请尝试此操作

Express 服务器正在侦听端口5000在您的 React 应用程序的package.json

添加 `"proxy": "http://localhost:5000/" 像这样

 "scripts": {
    .....
    ....
  },

  "proxy": "http://localhost:5000/"
  ,

  "eslintConfig": {
    .....
    ...
  },

在向您的 API 发出请求时,例如获取用户的数据

const fetchUser = (userId) => {
    
     const res = await axios.get(`/api/users/${userId}`)
     console.log(res.data)
}

PS:不要忘记/ in /api/users.... ,这让我哭了好几天。 这么傻的事。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM