Chapter 4,6: prettier updates and web framework samples

This commit is contained in:
Beth Griggs
2020-05-31 19:31:42 +01:00
parent b43bf2c378
commit 0d8170c265
43 changed files with 4820 additions and 242 deletions
+34 -32
View File
@@ -1,48 +1,50 @@
const http = require('http')
const fs = require('fs')
const path = require('path')
const http = require("http");
const fs = require("fs");
const path = require("path");
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
const form = fs.readFileSync(path.join(__dirname, "public", "form.html"));
http.createServer((req, res) => {
if (req.method === 'GET') {
get(res)
return
http
.createServer((req, res) => {
if (req.method === "GET") {
get(res);
return;
}
if (req.method === 'POST') {
post(req, res)
return
if (req.method === "POST") {
post(req, res);
return;
}
error(405, res)
}).listen(3000)
error(405, res);
})
.listen(3000);
function get(res) {
res.writeHead(200, {
'Content-Type': 'text/html'
})
res.end(form)
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(form);
}
function post(req, res) {
if (req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
error(415, res)
return
}
if (req.headers["content-type"] !== "application/x-www-form-urlencoded") {
error(415, res);
return;
}
let input = '';
let input = "";
req.on('data', chunk => {
input += chunk.toString()
})
req.on("data", (chunk) => {
input += chunk.toString();
});
req.on('end', () => {
console.log(input);
res.end(http.STATUS_CODES[200])
})
req.on("end", () => {
console.log(input);
res.end(http.STATUS_CODES[200]);
});
}
function error(code, res) {
res.statusCode = code
res.end(http.STATUS_CODES[code])
}
res.statusCode = code;
res.end(http.STATUS_CODES[code]);
}