簡體   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