heroku 如何配置我的服务器以使用固定的静态IP?

eoxn13cs  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(140)

我已经发送了一个GET请求使用冲突的氏族API和axios,并提供了身份验证,使其在本地工作,但它不工作时,部署为heroku使用动态IP地址。
我正在寻找使用静态IP地址,Heroku将使用它来授权我的API请求。我选择了fixie,但我不认为我的服务器实际上是使用静态IP,因为当导航到端点时,页面失败,网络选项卡显示一个远程连接,似乎是一个heroku的IP地址。本质上,我需要将一个IP列入白名单。
下面是我的代码:

require("dotenv").config();
const express = require("express");
const axios = require("axios");
const app = express();
const path = require('path');
const url = require('url');
const fixieUrl = url.parse(process.env.FIXIE_URL);
const requestUrl = url.parse('https://api.clashofclans.com/v1/players/%232889v22uq');
// const URL = "https://api.clashofclans.com/v1/players/%232889v22uq";

const options = {
  headers: {
    Host: requestUrl.host,
    'Proxy-Authorization': `Basic ${Buffer.from(fixieUrl.auth).toString('base64')}`,
    "Authorization": `Bearer ${process.env.API_TOKEN}`
  },
  host: fixieUrl.hostname,
  port: fixieUrl.port,
  path: requestUrl.href,
};

app.get("/api", (req, res) => {

  const clashReq = async () => {
    try {
      const response = await axios.get(requestUrl, options);

      const {
        name,
        townHallLevel,
        trophies,
        bestTrophies,
        builderHallLevel,
        league: {
          name: leagueName,
          iconUrls: { medium: mediumIcon },
        },
        legendStatistics: {
          previousSeason: { trophies: previousTrophies},
          bestSeason: { trophies: bestSeasonTrophies},
          currentSeason: { trophies: currentTrophies},
        },
      } = response.data;
      
      res.json({
          name,
          townHallLevel,
          trophies,
          bestTrophies,
          builderHallLevel,
          leagueName,
          mediumIcon,
          previousTrophies,
          bestSeasonTrophies,
          currentTrophies
        }
      );
    } catch (error) {
      console.log(error);
    }
  };

  clashReq();
 

  console.log(res.statusCode);
  
});


if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "/client/build")));
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "/client/build", "index.html"));
  });
}

app.listen(process.env.PORT || 3001, () => {
  console.log(`Server running`);
});
qf9go6mv

qf9go6mv1#

Axios可以通过一个现成的代理发出HTTPS请求。你只需要在options中提供一个proxy配置对象:

const axios = require('axios');
const url = require('url');
const fixieUrl = url.parse(process.env.FIXIE_URL);
const fixieAuth = fixieUrl.auth.split(':');

axios.get('https://example.com', {
  proxy: {
    protocol: 'http',
    host: fixieUrl.hostname,
    port: fixieUrl.port,
    auth: {username: fixieAuth[0], password: fixieAuth[1]}
  }
}).then(response => {
  console.log(response.status);
});

如果您这样做,您可以移除Proxy-AuthorizationHost信头,以及明确的hostport和和path选项。
Axios在幕后所做的是向Fixie发出CONNECT请求,以打开一个到远程的HTTP tunnel,然后通过该隧道向远程发出请求。这与HTTP请求的代理方式不同,但Axios将这种差异抽象化。

相关问题