proski_neki/index.js

78 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2022-09-20 10:54:35 +02:00
const express = require("express");
const http = require('http');
const fetch = require('node-fetch');
const https = require('https');
const bodyParser = require('body-parser');
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use('/proxy', async (req, res) => {
try {
// check if there is bearer token with value e8a8aead-95b5-47d0-9a10-2b7478f151bd
if (req.headers.authorization != 'Bearer e8a8aead-95b5-47d0-9a10-2b7478f151bd') {
res.status(401).json({
success: false,
code: 401
});
return;
}
// check if there is a proxy-target-url provided in header
if (!req.headers['proxy-target-url']) {
res.status(400).json({
success: false,
code: 400
});
return;
}
// copy over the headers from the request, while removing the authorization and Proxy-Target-URL headers
let headers = {};
for (let key in req.headers) {
if (key != 'authorization' && key != 'proxy-target-url') {
headers[key] = req.headers[key];
}
}
headers['host'] = null;
// print request body
// console.log(req.body);
let response = await fetch(req.headers['proxy-target-url'], {
method: req.method,
headers: headers,
body: req.method == 'GET' ? null : JSON.stringify(req.body),
agent: httpsAgent
});
// return the response, with the response header, status code and body
console.log(`[${new Date().toLocaleString('bs-Latn-BA')}] ${req.method} ${req.headers['proxy-target-url']}: ${response.status}`);
res.status(response.status).json({
success: true,
headers: response.headers,
status: response.status,
data: req.headers['proxy-target-url'].includes('https://najava.hzinfra.hr/hzinfo/default.asp') ? await response.buffer() : await response.text(),
sent: {
url: req.headers['proxy-target-url'],
method: req.method,
headers: headers,
body: req.body,
}
});
} catch (e) {
console.log(e);
res.status(500).json({
success: false,
code: 500
})
return;
}
})
http.createServer(app).listen(1234, async () => {
console.log("Server is running on port 1234");
});