forked from github/github-app-js-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
61 lines (56 loc) · 1.61 KB
/
routes.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
import fs from "fs";
import { storage } from "./storage.js";
import { queryStringToJson } from "./helpers.js";
export const routes = {
home(req, res) {
fs.readFile("./home.html", function (err, data) {
if (err) {
res.writeHead(404);
res.write("Errors: File not found");
return res.end();
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.write(data);
return res.end();
});
},
form(req, res) {
fs.readFile("./form.html", function (err, data) {
if (err) {
res.writeHead(404);
res.write("Errors: File not found");
return res.end();
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.write(data);
return res.end();
});
},
submitForm(req, res) {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString(); // convert Buffer to string
});
req.on("end", () => {
console.log(body);
let bodyJson = queryStringToJson(body);
const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
bodyJson.ip = ip;
const serverTimestamp = new Date().toISOString();
bodyJson.serverTimestamp = serverTimestamp;
storage.save(bodyJson);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.write(
"<h1>Form data saved ☑️</h1>\n<pre>" +
JSON.stringify(bodyJson, null, 2) +
"</pre>",
);
return res.end();
});
},
default(req, res) {
res.writeHead(404);
res.write("Path not found!");
return res.end();
},
};