Node.js & Express.js - A Refresher
1. What is Node.js?
- Like Browser is one host environment of that Javascript of frontend, Node.js is a host environment for Javascript of backend
- Chrome's Javascript engines V8 has all been cloned and is now maintained as a standalone project working without a browser and enriched with some extra APIs that is basically Node.js, it allows us to run Javascript outside of the browser
- Compare to V8, Node.js dropped some APIs(e.g. DOM API), and added some APIs(e.g. Filesystem)
2. A Simple Node.js Code
- Node.js code are just normal javascript code with extra node api
- In Node.js runtime environment, there are a few globally function (e.g., require)
- Between different Node.js module (javascript file), we can transfer object through require and export
A simple Node.js Code:
const fs = require("fs");
const userName = "Light";
fs.writeFile("./user-data.txt", "Name: " + userName, (error) => {
if (error) {
console.log(error);
return;
}
console.log("Wrote file successfully!");
});
3. Sending Requests & Responses
- Use Node.js http module to create a server
- When server receive GET request from browser then it pass response with a HTML form to client
- When server receive POST request from client then is extract data from the request and then pass back to client through response
A simple Node.js server:
// ./app.js
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Incoming request...");
console.log("Request http method:", req.method);
console.log("Request url:", req.url);
if (req.method === "POST") {
let body = "";
req.on("end", () => {
console.log("POST request data:", body);
const userName = body.split("=")[1];
res.end(`<p>Got the POST request!,
The username is: ${userName}</p>`);
});
req.on("data", (chunk) => {
body += chunk;
});
} else {
res.setHeader("Content-Type", "text/html");
res.end(`
<form method="POST">
<input type="text" name="username" />
<button type="submit">Create User</button>
</form>
`);
}
});
server.listen(5000);
4. What is Express.js?
- Express.js is a framework for Node.js
- It makes building web apps, server side code much easier
- Express is middleware focused
5. Adding Express.js
- In express every incoming request or senting back response is funneled through a bunch of middleware functions
- You call next function if you don't want to send the response in this middleware but to forward the request to the next middleware in line
- If you're not calling next, then any middleware after this middleware, if we had more than one, will not be reached by this request
Using Express.js as Server:
// ./app.js
const express = require("express");
const app = express();
app.use((req, res, next) => {
let body = "";
req.on("end", () => {
const userName = body.split("=")[1];
if (userName) {
req.body = { name: userName };
}
next();
});
req.on("data", (chunk) => {
body += chunk;
});
});
app.use((req, res, next) => {
if (req.body) {
res.send(`<p>Got the POST request!,
The username is: ${req.body.name}</p>`);
} else {
res.send(`
<form method="POST">
<input type="text" name="username" />
<button type="submit">Create User</button>
</form>
`);
}
});
app.listen(5000, () => {
console.log("Server running at port 5000...");
});
6. Advantages of Express.js
- In express app, we can not just use custom middleware function but also third party library middleware function
- body-parser can parse data about request and attach the parsed result to body property of request
- Express app funnel request to middleware function based on HTTP method and path (slash and string combination after the domain)
- Different from other Express app's HTTP methods match path exactly, app.use function match path wildly
A simple Express.js app:
// ./app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const inputFieldName = "username";
let requestCounter = 0;
// work for all requests that start with slash after the domain
app.use("/", (req, res, next) => {
console.log(
`Middleware in the first app.use!,
get request ${++requestCounter} times!`
);
next();
});
app.use(bodyParser.urlencoded({ extended: false }));
// request's path has to be exact match /user
app.post("/user", (req, res, next) => {
res.send(`<p>Got the POST request,
The username is: ${req.body[inputFieldName]}</p>`);
});
// request not just filtering by HTTP method but also by path
app.get("/", (req, res, next) => {
res.send(`
<form action="/user" method="POST">
<input type="text" name="${inputFieldName}" />
<button type="submit">Create User</button>
</form>
`);
});
app.listen(5000, () => {
console.log("Server running at port 5000...");
});
7. Source code
Source code of the article: https://github.com/lightrao/node-express-refresher
Comments
Post a Comment