-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
132 lines (107 loc) · 2.83 KB
/
index.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const http = require('http');
let requestLogs = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const requestLog = {
date : new Date(),
method: req.method,
headers: req.headers,
body: body,
};
requestLogs.push(requestLog);
// Log the request information to the console
console.log('Incoming Request:\n', JSON.stringify(requestLog, null, 2));
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Request logged to console!\n');
});
});
const PORT = 3001;
server.listen(PORT, () => {
console.log(`Node request bin is listening on port ${PORT}`);
});
const webPageServer = http.createServer((req, res) => {
const tableRows = requestLogs.map(r => `
<tr>
<td>${r.date.getHours()}:${r.date.getMinutes()}:${r.date.getSeconds()}.${r.date.getMilliseconds()}</td>
<td>${r.method}</td>
<td><pre>${JSON.stringify(r.headers, null, 4 )}</pre></td>
<td><pre>${JSON.stringify(r.body,null,4)}</pre></td>
<td>${createCurlString(r)}</td>
</tr>
`).join('');
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Roboto, sans-serif;
}
table {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
}
/* Style the table header */
th {
background-color: #f2f2f2;
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
/* Style alternating rows */
tr:nth-child(even) {
background-color: #f2f2f2;
}
/* Style table cells */
td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
<meta http-equiv="refresh" content="2">
<title>Node request bin</title>
</head>
<body>
<h1>Incoming request </h1>
<p>Send request to http://127.0.0.1:${PORT}</p>
<table border="1">
<thead>
<tr>
<th>Date</th>
<th>Method</th>
<th>Header</th>
<th>Body</th>
<th>Curl</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
</body>
</html>
`;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlContent);
});
webPageServer.listen(3002, () => {
console.log('Web page server is listening on port 3002');
});
function createCurlString(requestOptions) {
const { method, url, headers, body } = requestOptions;
let curlString = `curl -X ${method} '127.0.0.1:${PORT}'`;
/*
for (const header in headers) {
curlString += ` -H '${header}:${headers[header]}'`;
}
*/
if (body) {
curlString += ` -d '${JSON.stringify(body)}'`;
}
return curlString;
}