UNPKG

3.01 kBJavaScriptView Raw
1var express = require('express'),
2 app = express(),
3 XMLHttpRequest = require("./xmlhttprequest").XMLHttpRequest;
4
5exports.getClientIp = function(req, headers) {
6 var ipAddress = req.connection.remoteAddress;
7
8 var forwardedIpsStr = req.header('x-forwarded-for');
9
10 if (forwardedIpsStr) {
11 // 'x-forwarded-for' header may return multiple IP addresses in
12 // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
13 // the first one
14 forwardedIpsStr += "," + ipAddress;
15 } else {
16 forwardedIpsStr = "" + ipAddress;
17 }
18
19 headers['x-forwarded-for'] = forwardedIpsStr;
20
21 return headers;
22};
23
24
25exports.sendData = function(port, options, data, res, callBackOK, callbackError) {
26 var xhr, body, result;
27
28 callbackError = callbackError || function(status, resp) {
29 console.log("Error: ", status, resp);
30 res.statusCode = status;
31 res.send(resp);
32 };
33 callBackOK = callBackOK || function(status, resp, headers) {
34 res.statusCode = status;
35 for (var idx in headers) {
36 var header = headers[idx];
37 res.setHeader(idx, headers[idx]);
38 }
39 console.log("Response: ", status);
40 console.log(" Body: ", resp);
41 res.send(resp);
42 };
43
44 var url = port+"://" + options.host + ":" + options.port + options.path;
45 xhr = new XMLHttpRequest();
46 xhr.open(options.method, url, true);
47 if (options.headers["content-type"]) {
48 xhr.setRequestHeader("Content-Type", options.headers["content-type"]);
49 }
50 for (var headerIdx in options.headers) {
51 switch (headerIdx) {
52 // Unsafe headers
53 case "host":
54 case "connection":
55 case "referer":
56// case "accept-encoding":
57// case "accept-charset":
58// case "cookie":
59// case "content-length":
60 case "origin":
61 break;
62 default:
63 xhr.setRequestHeader(headerIdx, options.headers[headerIdx]);
64 break;
65 }
66 }
67
68 xhr.onerror = function(error) {
69 }
70 xhr.onreadystatechange = function () {
71
72 // This resolves an error with Zombie.js
73 if (flag) {
74 return;
75 }
76
77 if (xhr.readyState === 4) {
78 flag = true;
79 if (xhr.status < 400) {
80 callBackOK(xhr.status, xhr.responseText, xhr.getAllResponseHeadersList());
81 } else {
82 callbackError(xhr.status, xhr.responseText);
83 }
84 }
85 };
86
87 var flag = false;
88 // console.log("Sending ", options.method, " to: " + url);
89 // console.log(" Headers: ", options.headers);
90 // console.log(" Body: ", data);
91 if (data !== undefined) {
92 try {
93 xhr.send(data);
94 } catch (e) {
95 callbackError(e.message);
96 return;
97 }
98 } else {
99 try {
100 xhr.send();
101 } catch (e) {
102 callbackError(e.message);
103 return;
104 }
105 }
106}
\No newline at end of file