-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (63 loc) · 2.08 KB
/
server.js
File metadata and controls
72 lines (63 loc) · 2.08 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
const express = require("express");
const axios = require("axios");
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.static("src"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/src/index.html");
});
app.post("/api/ping", async (req, res) => {
const url = req.body?.url;
const method = req.body?.method;
const headers = req.body?.headers;
const body = req.body?.body;
if (!url) {
return res.json({ error: true, message: "URL is required to perform a request." });
}
const startTime = Date.now();
try {
const response = await axios({
method,
url,
headers,
data: body,
});
const time = Date.now() - startTime;
const size = JSON.stringify(response.data)?.length || 0;
res.json({
status: response.status,
statusText: response.statusText,
data: response.data,
headers: response.headers,
reqHeaders: response.config.headers,
time,
size
});
} catch (error) {
const time = Date.now() - startTime;
if (error.response) {
const size = JSON.stringify(error.response.data)?.length || 0;
// Axios throws an error for status codes like 404 or 500. We still want to return the response to the frontend.
res.json({
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data,
headers: error.response.headers,
reqHeaders: error.response.config?.headers || error.config?.headers,
time,
size
});
} else {
// Network errors or invalid URLs
res.json({
error: true,
message: error.message,
reqHeaders: error.config?.headers
});
}
}
});
app.listen(port, () => {
console.log(`PingPoint is running on http://localhost:${port}`);
});