This repository was archived by the owner on Jan 14, 2025. It is now read-only.
forked from JogoShugh/VersionOne.MetaTrain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (70 loc) · 2.14 KB
/
server.js
File metadata and controls
83 lines (70 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var bodyParser = require('body-parser');
var request = require('request');
var express = require('express');
var app = express();
var cors = require('cors');
app.use(bodyParser.text({ type : 'application/json' }));
app.use(bodyParser.text({ type : 'application/xml' }));
app.use(cors());
app.use(express.static(__dirname + '/public'));
function getUrl(req) {
var url = decodeURIComponent(req.originalUrl.substr(8, req.originalUrl.length - 8));
return url;
}
function getHeaders(headers) {
var result = {};
for (h in headers) {
if (h == 'host' || h == 'origin' || h == 'referer' || h == 'accept-encoding')
continue;
result[h] = headers[h];
}
return result;
}
function addHeaders(response, headers) {
for (h in headers) {
response.setHeader(h, headers[h]);
}
}
function responseError(response, msg) {
response.type('application/json; charset=utf-8');
var error = { error: msg };
response.end(JSON.stringify(error));
}
app.get('/pt', function (req, res, next) {
try {
var url = getUrl(req);
var options = {
url: url,
method: 'GET',
headers: getHeaders(req.headers)
};
request(options, function (error, response, body) {
if (error) throw error.message;
addHeaders(res, getHeaders(response.headers));
res.end(body);
});
} catch (exception) {
responseError(res, exception);
}
});
app.post('/pt', function (req, res, next) {
try {
var options = {
url: getUrl(req),
method: 'POST',
body: req.body,
headers: getHeaders(req.headers)
};
request(options, function (error, response, body) {
if (error) throw error.message;
addHeaders(res, getHeaders(response.headers));
res.status(200).send(body);
});
} catch (exception) {
responseError(res, exception);
}
});
var port = parseInt(process.env.PORT) || 5000;
app.listen(port, function () {
console.log('VersionOne.MetaTrain with CORS Proxy listening on port ' + port);
});