Chapter 4,6: prettier updates and web framework samples
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<label for="userfile">File:</label>
|
||||
<input type="file" id="userfile" name="userfile"><br>
|
||||
<input type="submit">
|
||||
<label for="userfile">File:</label>
|
||||
<input type="file" id="userfile" name="userfile" /><br />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
|
||||
@@ -1,55 +1,58 @@
|
||||
const fs = require('fs')
|
||||
const http = require('http')
|
||||
const path = require('path')
|
||||
const fs = require("fs");
|
||||
const http = require("http");
|
||||
const path = require("path");
|
||||
|
||||
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
|
||||
const form = fs.readFileSync(path.join(__dirname, "public", "form.html"));
|
||||
|
||||
const formidable = require('formidable')
|
||||
const formidable = require("formidable");
|
||||
|
||||
|
||||
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 (!/multipart\/form-data/.test(req.headers['content-type'])) {
|
||||
error(415, res)
|
||||
return
|
||||
}
|
||||
if (!/multipart\/form-data/.test(req.headers["content-type"])) {
|
||||
error(415, res);
|
||||
return;
|
||||
}
|
||||
|
||||
const form = formidable({
|
||||
multiples: true,
|
||||
uploadDir: './uploads'
|
||||
const form = formidable({
|
||||
multiples: true,
|
||||
uploadDir: "./uploads",
|
||||
});
|
||||
|
||||
form.parse(req, (err, fields, files) => {
|
||||
if (err) return err;
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
|
||||
form.parse(req, (err, fields, files) => {
|
||||
if (err) return err
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json'
|
||||
});
|
||||
res.end(JSON.stringify({
|
||||
fields,
|
||||
files
|
||||
}))
|
||||
})
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
fields,
|
||||
files,
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function error(code, res) {
|
||||
res.statusCode = code
|
||||
res.end(http.STATUS_CODES[code])
|
||||
}
|
||||
res.statusCode = code;
|
||||
res.end(http.STATUS_CODES[code]);
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
const http = require('http')
|
||||
const http = require("http");
|
||||
|
||||
const HOSTNAME = process.env.HOSTNAME || '0.0.0.0'
|
||||
const PORT = process.env.PORT || 8080
|
||||
const HOSTNAME = process.env.HOSTNAME || "0.0.0.0";
|
||||
const PORT = process.env.PORT || 8080;
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method !== 'GET') return error(res, 405)
|
||||
if (req.url === '/todo') return todo(res)
|
||||
if (req.url === '/') return index(res)
|
||||
error(res, 404)
|
||||
if (req.method !== "GET") return error(res, 405);
|
||||
if (req.url === "/todo") return todo(res);
|
||||
if (req.url === "/") return index(res);
|
||||
error(res, 404);
|
||||
});
|
||||
|
||||
function error(res, code) {
|
||||
res.statusCode = code
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`)
|
||||
res.statusCode = code;
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`);
|
||||
}
|
||||
|
||||
function todo(res) {
|
||||
res.end('[{"task_id": 1, "description": "walk dog"}]}')
|
||||
res.end('[{"task_id": 1, "description": "walk dog"}]}');
|
||||
}
|
||||
|
||||
function index(res) {
|
||||
res.end('{"name": "todo-server"}')
|
||||
res.end('{"name": "todo-server"}');
|
||||
}
|
||||
|
||||
server.listen(PORT, HOSTNAME, () => {
|
||||
console.log('Server listening on', server.address())
|
||||
})
|
||||
console.log("Server listening on", server.address());
|
||||
});
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
const https = require('https')
|
||||
const https = require("https");
|
||||
|
||||
// http.get('http://example.com', (res) => res.pipe(process.stdout))
|
||||
|
||||
const payload = `{
|
||||
"name": "Beth",
|
||||
"job": "Software Engineer"
|
||||
}`
|
||||
}`;
|
||||
|
||||
const opts = {
|
||||
method: 'POST',
|
||||
hostname: 'postman-echo.com',
|
||||
path: '/post',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload)
|
||||
}
|
||||
}
|
||||
method: "POST",
|
||||
hostname: "postman-echo.com",
|
||||
path: "/post",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
};
|
||||
|
||||
const req = https.request(opts, (res) => {
|
||||
process.stdout.write('Status Code: ' + res.statusCode + '\n')
|
||||
process.stdout.write('Body: ')
|
||||
res.pipe(process.stdout)
|
||||
})
|
||||
process.stdout.write("Status Code: " + res.statusCode + "\n");
|
||||
process.stdout.write("Body: ");
|
||||
res.pipe(process.stdout);
|
||||
});
|
||||
|
||||
req.on('error', (err) => console.error('Error: ', err))
|
||||
req.on("error", (err) => console.error("Error: ", err));
|
||||
|
||||
req.end(payload)
|
||||
req.end(payload);
|
||||
|
||||
@@ -1,56 +1,57 @@
|
||||
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/json') {
|
||||
error(415, res)
|
||||
return
|
||||
if (req.headers["content-type"] !== "application/json") {
|
||||
error(415, res);
|
||||
return;
|
||||
}
|
||||
|
||||
let input = "";
|
||||
|
||||
req.on("data", (chunk) => {
|
||||
input += chunk.toString();
|
||||
});
|
||||
|
||||
req.on("end", () => {
|
||||
const parsed = JSON.parse(input);
|
||||
|
||||
if (parsed.err) {
|
||||
error(400, "Bad Request", res);
|
||||
return;
|
||||
}
|
||||
|
||||
let input = '';
|
||||
|
||||
req.on('data', chunk => {
|
||||
input += chunk.toString()
|
||||
})
|
||||
|
||||
req.on('end', () => {
|
||||
const parsed = JSON.parse(input)
|
||||
|
||||
if (parsed.err) {
|
||||
error(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
|
||||
console.log('Received data: ', parsed)
|
||||
res.end('{"data": ' + input + "}")
|
||||
})
|
||||
|
||||
console.log("Received data: ", parsed);
|
||||
res.end('{"data": ' + input + "}");
|
||||
});
|
||||
}
|
||||
|
||||
function error(code, res) {
|
||||
res.statusCode = code
|
||||
res.end(http.STATUS_CODES[code])
|
||||
}
|
||||
res.statusCode = code;
|
||||
res.end(http.STATUS_CODES[code]);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
<form method="POST">
|
||||
<label for="forename">Forename:</label>
|
||||
<input id="forename" name="forename">
|
||||
<label for="surname">Surname:</label>
|
||||
<input id="surname" name="surname">
|
||||
<input type="submit" value="Submit">
|
||||
<label for="forename">Forename:</label>
|
||||
<input id="forename" name="forename" />
|
||||
<label for="surname">Surname:</label>
|
||||
<input id="surname" name="surname" />
|
||||
<input type="submit" value="Submit" />
|
||||
</form>
|
||||
|
||||
<script>
|
||||
document.forms[0].addEventListener('submit', (event) => {
|
||||
event.preventDefault()
|
||||
document.forms[0].addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
let data = {
|
||||
'forename': document.getElementById('forename').value,
|
||||
'surname': document.getElementById('surname').value
|
||||
};
|
||||
console.log('data', data);
|
||||
let data = {
|
||||
forename: document.getElementById("forename").value,
|
||||
surname: document.getElementById("surname").value,
|
||||
};
|
||||
console.log("data", data);
|
||||
|
||||
fetch('http://localhost:3000', {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
}).then(function (response) {
|
||||
console.log(response);
|
||||
return response.json();
|
||||
});
|
||||
fetch("http://localhost:3000", {
|
||||
method: "post",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
}).then(function (response) {
|
||||
console.log(response);
|
||||
return response.json();
|
||||
});
|
||||
</script>
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
const nodemailer = require("nodemailer")
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: "localhost",
|
||||
port: 4321
|
||||
})
|
||||
host: "localhost",
|
||||
port: 4321,
|
||||
});
|
||||
|
||||
transporter.sendMail({
|
||||
from: 'beth@example.com',
|
||||
to: 'laddie@example.com',
|
||||
transporter.sendMail(
|
||||
{
|
||||
from: "beth@example.com",
|
||||
to: "laddie@example.com",
|
||||
subject: "Hello",
|
||||
text: "Hello world!"
|
||||
}, (err, info) => {
|
||||
text: "Hello world!",
|
||||
},
|
||||
(err, info) => {
|
||||
if (err) {
|
||||
console.log(err)
|
||||
console.log(err);
|
||||
}
|
||||
console.log("Message Sent:", info)
|
||||
})
|
||||
console.log("Message Sent:", info);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
const SMTPServer = require("smtp-server").SMTPServer
|
||||
const SMTPServer = require("smtp-server").SMTPServer;
|
||||
|
||||
const PORT = 4321
|
||||
const PORT = 4321;
|
||||
|
||||
const server = new SMTPServer({
|
||||
disabledCommands: ['STARTTLS', 'AUTH'],
|
||||
logger: true
|
||||
})
|
||||
disabledCommands: ["STARTTLS", "AUTH"],
|
||||
logger: true,
|
||||
});
|
||||
|
||||
server.on('error', err => {
|
||||
console.error(err);
|
||||
})
|
||||
server.on("error", (err) => {
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
server.listen(PORT)
|
||||
server.listen(PORT);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
const fs = require('fs')
|
||||
const http = require('http')
|
||||
const fs = require("fs");
|
||||
const http = require("http");
|
||||
|
||||
const index = fs.readFileSync('public/index.html')
|
||||
const index = fs.readFileSync("public/index.html");
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.end(index)
|
||||
})
|
||||
res.setHeader("Content-Type", "text/html");
|
||||
res.end(index);
|
||||
});
|
||||
|
||||
server.listen(8080)
|
||||
server.listen(8080);
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
const WebSocket = require('ws')
|
||||
const ws = new WebSocket('ws://localhost:3000')
|
||||
const WebSocket = require("ws");
|
||||
const ws = new WebSocket("ws://localhost:3000");
|
||||
|
||||
ws.on('open', () => {
|
||||
console.log('Connected')
|
||||
})
|
||||
ws.on("open", () => {
|
||||
console.log("Connected");
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
console.log('Disconnected')
|
||||
})
|
||||
ws.on("close", () => {
|
||||
console.log("Disconnected");
|
||||
});
|
||||
|
||||
ws.on('message', (message) => {
|
||||
console.log('Received:', message)
|
||||
})
|
||||
ws.on("message", (message) => {
|
||||
console.log("Received:", message);
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
ws.send("Hello")
|
||||
}, 3000)
|
||||
ws.send("Hello");
|
||||
}, 3000);
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
<h1>Communicating with WebSockets</h1>
|
||||
|
||||
<input id="msg"><button id="send">Send</button>
|
||||
<input id="msg" /><button id="send">Send</button>
|
||||
<div id="output"></div>
|
||||
|
||||
<script>
|
||||
const ws = new WebSocket('ws://localhost:3000')
|
||||
const output = document.getElementById('output')
|
||||
const send = document.getElementById('send')
|
||||
const ws = new WebSocket("ws://localhost:3000");
|
||||
const output = document.getElementById("output");
|
||||
const send = document.getElementById("send");
|
||||
|
||||
send.addEventListener('click', () => {
|
||||
const msg = document.getElementById('msg').value
|
||||
ws.send(msg)
|
||||
output.innerHTML += log('Sent', msg)
|
||||
})
|
||||
send.addEventListener("click", () => {
|
||||
const msg = document.getElementById("msg").value;
|
||||
ws.send(msg);
|
||||
output.innerHTML += log("Sent", msg);
|
||||
});
|
||||
|
||||
function log(event, msg) {
|
||||
return '<p>' + event + ': ' + msg + '</p>'
|
||||
}
|
||||
function log(event, msg) {
|
||||
return "<p>" + event + ": " + msg + "</p>";
|
||||
}
|
||||
|
||||
ws.onmessage = function (e) {
|
||||
output.innerHTML += log('Received', e.data)
|
||||
}
|
||||
ws.onmessage = function (e) {
|
||||
output.innerHTML += log("Received", e.data);
|
||||
};
|
||||
|
||||
ws.onclose = function (e) {
|
||||
output.innerHTML += log('Disconnected', e.code)
|
||||
}
|
||||
ws.onclose = function (e) {
|
||||
output.innerHTML += log("Disconnected", e.code);
|
||||
};
|
||||
|
||||
ws.onerror = function (e) {
|
||||
output.innerHTML += log('Error', e.data)
|
||||
}
|
||||
ws.onerror = function (e) {
|
||||
output.innerHTML += log("Error", e.data);
|
||||
};
|
||||
</script>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
const WebSocket = require('ws')
|
||||
const WebSocket = require("ws");
|
||||
|
||||
const WebSocketServer = new WebSocket.Server({
|
||||
port: 3000
|
||||
})
|
||||
port: 3000,
|
||||
});
|
||||
|
||||
WebSocketServer.on('connection', (socket) => {
|
||||
socket.on('message', (msg) => {
|
||||
console.log('Received:', msg)
|
||||
if (msg === 'Hello') socket.send('World!')
|
||||
})
|
||||
})
|
||||
WebSocketServer.on("connection", (socket) => {
|
||||
socket.on("message", (msg) => {
|
||||
console.log("Received:", msg);
|
||||
if (msg === "Hello") socket.send("World!");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user