我已经发送了一个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`);
});
1条答案
按热度按时间qf9go6mv1#
Axios可以通过一个现成的代理发出HTTPS请求。你只需要在
options
中提供一个proxy
配置对象:如果您这样做,您可以移除
Proxy-Authorization
和Host
信头,以及明确的host
、port
和和path
选项。Axios在幕后所做的是向Fixie发出
CONNECT
请求,以打开一个到远程的HTTP tunnel,然后通过该隧道向远程发出请求。这与HTTP请求的代理方式不同,但Axios将这种差异抽象化。