-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
44 lines (38 loc) · 1.43 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
const fs = require('fs');
const homePage = require('./index.html');
const requestHandler = (req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(homePage);
// res.write('<html>');
// res.write('<head><title>Enter Message</title></head>');
// res.write('<body><form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form></body>');
// res.write('</html>');
return res.end();
}
if (url == '/message' && method === 'POST') {
const body = [];
req.on('data', (chunk) => {
body.push(chunk);
console.log(chunk)
});
return req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
console.log(parsedBody);
fs.writeFile('message.txt', message, (err) => {
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
});
}
res.write('<html>');
res.write('<head><title>My First Page</title></head>');
res.write('<body><h1>Hello from Node.js server</h1></body>');
res.write('</html>');
res.end();
};
module.exports = requestHandler;