forked from GrosSacASac/JavaScript-Set-Up
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_from_handler.js
More file actions
71 lines (60 loc) · 1.9 KB
/
Copy pathnode_from_handler.js
File metadata and controls
71 lines (60 loc) · 1.9 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
// draft
// todo use https://github.com/felixge/node-formidable/
import http from "http";
import fs from "fs";
const PORT = 8000;
const staticsPath = `./`;
const FORM_URLENCODED = `application/x-www-form-urlencoded`;
const FORM_BYTES = `multipart/form-data`;
const staticResponses = {
[`/form.html`]: {
[`file`]: `${staticsPath}/form.html`,
[`Content-Type`]: `text/html`
},
};
const handleStatic = (request, response) => {
if (staticResponses.hasOwnProperty(request.url)) {
response.writeHead(200, {[`Content-Type`]: staticResponses[request.url][`Content-Type`]});
fs.createReadStream(staticResponses[request.url][`file`]).pipe(response);
} else {
response.writeHead(404, {[`Content-Type`]: `text/plain`});
response.end(`404 Wrong url - not found`);
}
};
const handleSubmit = (request, response) => {
if (request.headers[`content-type`] !== FORM_URLENCODED && !request.headers[`content-type`].includes(FORM_BYTES)) {
response.write(`not ok`);
response.write(request.headers[`content-type`]);
response.end();
return;
}
const buffers = [];
request.on(`data`, buffer => {
buffers.push(buffer);
});
request.on(`end`, () => {
const asString = buffers.map(String).join(``);
console.log(asString);
response.write(asString);
response.end();
});
};
const server = http.createServer((request, response) => {
if (request.method === `GET`) {
handleStatic(request, response);
return;
}
if (request.method === `POST` && request.url === `/submit`) {
handleSubmit(request, response);
return;
}
console.log(request.url);
response.setHeader(`Content-Type`, `text/plain`);
response.writeHead(405);
response.end(`Only use GET please`);
});
const start = function () {
server.listen(PORT);
console.log(`Listening on ${PORT}`);
};
start();