homepage/src/pages/api/proxy.js

60 lines
1.5 KiB
JavaScript
Raw Normal View History

import https from "https";
2022-09-07 16:53:24 +03:00
2022-08-25 20:57:25 +03:00
import getRawBody from "raw-body";
2022-08-24 10:44:35 +03:00
import { httpRequest, httpsRequest } from "utils/proxy/http";
2022-08-25 20:57:25 +03:00
export const config = {
api: {
bodyParser: false,
},
};
2022-08-25 17:57:18 +03:00
2022-08-24 10:44:35 +03:00
export default async function handler(req, res) {
2022-08-25 20:57:25 +03:00
const headers = ["X-API-Key", "Authorization"].reduce((obj, key) => {
2022-09-07 16:53:24 +03:00
if (req.headers && Object.prototype.hasOwnProperty.call(req.headers, key.toLowerCase())) {
// eslint-disable-next-line no-param-reassign
2022-08-24 10:44:35 +03:00
obj[key] = req.headers[key.toLowerCase()];
}
return obj;
}, {});
const url = new URL(req.query.url);
2022-08-25 17:57:18 +03:00
if (url.protocol === "https:") {
// this agent allows us to bypass the certificate check
// which is required for most self-signed certificates
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
2022-08-26 22:33:54 +03:00
const [status, contentType, data] = await httpsRequest(url, {
2022-08-25 17:57:18 +03:00
agent: httpsAgent,
method: req.method,
2022-09-07 16:53:24 +03:00
headers,
2022-08-25 20:57:25 +03:00
body:
2022-09-07 16:53:24 +03:00
req.method === "GET" || req.method === "HEAD"
2022-08-25 20:57:25 +03:00
? null
: await getRawBody(req, {
encoding: "utf8",
}),
2022-08-25 17:57:18 +03:00
});
2022-08-26 22:33:54 +03:00
res.setHeader("Content-Type", contentType);
2022-08-25 17:57:18 +03:00
return res.status(status).send(data);
}
2022-09-07 16:53:24 +03:00
const [status, contentType, data] = await httpRequest(url, {
method: req.method,
headers,
body:
req.method === "GET" || req.method === "HEAD"
? null
: await getRawBody(req, {
encoding: "utf8",
}),
});
res.setHeader("Content-Type", contentType);
return res.status(status).send(data);
2022-08-24 10:44:35 +03:00
}