2026-08-23 16:41

Status:


BDAN - Module 3 - Express Web Application Framework

==Express Web Application Framework

  • Extending Node. js:
    • The default Node.js framework provides a limited set of features for building web applications unfortunately
    • You can still set up a pretty simple one using HTTP requests, but connecting databases, processing files, authentication, and routing can be pretty hard
    • Generally, developers would rely on some other third-party software in order to make Node a bit more usable and more friendly to generally work with
    • Pasted image 20260823164911.png
    • The above hand is an example of how in Node you might handle parsing a string of data after sending an HTTP request to get data from some weather service that is using a xml file format for example
    • In node, the response.on('data' function(chunk)) code basically stores that data in a given buffer object that you can then process with the response.on('end' function()) which in the above hand uses a lot of fucky-wucky JS syntax in order to parse the string
    • Finally then the resultCallback(null, result); callback method sends back to whatever service would have requests the data, the result of the processed data from the third-party website, allowing for quick and non-blocking processing and displaying of a temperature basically.
    • This is all fun and dandy, but is a LOT of code for something that is pretty simple, and takes a good understanding of node to really know what you are looking at
    • You also have to make use a string format to parse XML, which is bad is causes you to ignore the structure of XML and might lead you to parse out malformed data as well
    • Pasted image 20260823165620.png
    • To sort of for-go this whole process, you can use something like the xml2js Node package which can help you parse a string of XML elements into a javascript object, making it MUCH easier to deal with
    • Third party packages like this might be useful and good of course, but you need to make sure you follow all legal licenses and that they match your legal license as well whenever you use them
    • You can manage these node packages and modules with the Node Package Manager (npm)
  • Introduction to Web Frameworks:
    • Node. js IS NOT A FRAMEWORK it is instead actually considered a runtime environment which is kind of more so like an interpreter that lets javascript run outside of a browser

    • A runtime environment like Node. js are generally the hardware and software that can execute programs with a particular codebase

    • Node Framework is more so like the skeleton that is hiding under all of the code that you yourself write, it is generally a bunch of imported code that determines the structure of your program

    • For more information about frame works, just click on Frameworks to see all other notes related to them

    • Basically though the main point is to use Node. js you NEED A WEB FRAMEWORK to work alongside it, and these things are called node frameworks

    • There are TWO approaches to building back ends (although a single application can use both approaches at once)

      • Model-View-Controller (MVC) - this divides out the back-end into THREE given components (can you guess what they are)

        • Model - this manages the data of the application, it interacts with the database and handles data logic

        • View - this is responsible for rendering a presentation of the data so that way someone can see it, it is passed this data from the model

        • Controller - This as you can assume, controls/regulates the flow of the data between the model and the view, it processes the data provided by the user and sends it to the view

      • This kind of approach is generally really good for applications that need separation of the data, from the data presentation, and from the manipulation of data

      • Some popular frameworks that can implement MVC are Koa, Django, Express, and NestJS

      • Representational state transfer application programming interface (REST API) allow for multiple web services to communicate with each other and with the clients, sort of forming this web of communication between each of the services

      • RESTful APIs have some constraints though

        • Client and server code are independent of each other, MEANING client side code can be updated without interfering from the server, and vice-versa
        • RESTful APIs are stateless meaning that the client DOES NOT KNOW the state of the server and vice-versa
        • This means that the two APIs communication operations on resources, and that the communications do not rely on an implementations of a single API, letting them sort of modular and not really worry about one another
      • When a client uses a REST API to get some of data from the Web Service Server, using a GET, POST, PATCH resource or something like that, the web server responds with a state of the resource to that client

      • This generally sends data over using something like a JSON Payload, or status code, but can be other things like XML and what not as well. This is similar to what the MidasCloud - Project Overview-Architecture (README.md) for project obsidian portal backend actually does too

    • POPULAR NODE. JS FRAMEWORKS

    • Express this is my personal favorite (the only one I know how to use) and is very popular in the general community as well

    • It is primarily used for routing and middleware, see Node.js + Express — Backend Fundamentals for more on those

    • Express has a small learning curve because it generally uses JS, and it is also easy to just implement a MVC architecture pattern in there as well

    • Express is really good because it has things to let you handle HTTP requests a lot easier and also is able to handle multiple different operations concurrently

    • It is good for facilitating communication between a client and a server, and efficiently provides HTTP heads to URLs to get needed data requested by the client without all of the overload from Node

    • Koa this is designed by the same people who designed express, and they designed it to be a bit smaller, letting it be more robust for web applications and APIs

    • It uses Async functions such that callbacks are not even necessary, and has an increased error-handling ability

    • It is good for applications that: are high-performance, demanding, complex, and developed by large experienced teams

    • Socket.io best for apps with real-time bidirectional data exchange between clients and servers, meaning that it would be great for things like chatrooms, texting, video conferencing, etc

    • You can utilize WebSocket which is a different form of communication from HTTP, but still gets your data from point A to point B

    • This one is good if you need your server to push out data without request for that data from your client

    • Hapi.js is nice and open source, with a lot of cybersecurity built straight in, which is nice.

    • It also has a ton of built-in plugins so there is no need for unofficial third-party middleware unless you really need it

    • It is good for making things like Proxy servers and API servers as well, some more back-end kind of activity, the back-end for the back-end I guess

    • NestJS which is good for dynamic, scalable, and enterprise applications

    • it is super flexible with a lot of support for different libraries and an easy to implement MVC architecture

    • It is basically an extension of express and is built on top of express itself

    • It is also good for working with typescript, and is often used in tandem with the Angular Framework

  • Express Web Application Frameworks:
    • Express is a third-party module that provides a framework for building the back-end for web applications
    • It helps to extract the lower level details of back-end development, letting you easily handle things like API connects and data management and what not.
    • It is super good because it is easy to install and has a bunch of extra support that you let very quickly get a back-end up and running
    • It is good for handling different things like Routing, Databases, HTTP URL requests, authentication, and more
    • TWO purposes of Express
      • As an API - this basically lets you set up an HTTP interface to interact with the data layer of the application, and in this case the Data Requested is send back to the client in JSON format, using a res (response) object. This is mainly what MidasCloud - Project Overview-Architecture (README.md) for project does
      • res.json() is used to notify the client of the content-type being sent, like if it is an image or a text, and can also be used to turn data into JSON format
      • Setup templates with server-side rendering (SSR) - express is used to set up templates, and the data is sent from the client to the server via an HTTP request in conjunction with an template to dynamically write HTML, CSS, and JavaScript, and this code is then SENT BACK TO THE BROWSER AS TEXT, so it can be rendered
      • This is done using the res.render() method
    • Pasted image 20260823173524.png
    • The image displays basically how you get express to work inside of a given application, and it is very simple, the line const express = require('express) & const app = express() basically works similar to the http.createServer() function from node, where it creates a server for you. This app object is basically what you get from the express module which you import, and then it stores all of the functionality, letting you do things like use middleware or listen for incoming requests on a given port
    • Pasted image 20260823173757.png
    • Express is very simple to set up, you clear it as a dependency, use the npm command to install any given dependencies or modules for it, import the module where you want to write code, create the new app or route handler object, and then start listening to things with it on a certain port
    • Steps on how to install and set up express
    • Pasted image 20260823173931.png
    • Pasted image 20260823174129.png
    • The main information is in the image, but in the package.json file, you have things like the name, which is the name for the Node. js module
    • The given version of it that you want to install
    • A Description of the purpose of the module
    • Main, in which you indentify the Ndoe. js script as the entry point to the module
    • And then any dependencies that said module might need, this was covered inside of BDAN - Module 2 - Asynchronous I-O with callback programming
    • Pasted image 20260823174157.png
    • Pasted image 20260823174423.png
    • Generally as the diagram above says, you can use npm install which is going to look at the json file from above and use the package manager in order to properly set up every single thing you need, or you can directly install express using npm install express
    • This all goes into a node_module dir, which should be not included in a git repo of the project mind you because anyone can just download this from your package.json
    • There can also be multiple different node module repositories that host different versions of the same dependencies, meaning that you do not need to worry as deeply about version mismatching breaking your entire system
  • Introduction to Middleware & Routers:
    • Middleware is software that sits between applications, databases, or services and allows those different technologies to communicate. It creates seamless interactions for the end user in a distributed system.
    • Express is a Node. js web application framework used for web servers, APIs, and middleware It is mostly used on the server side to handle HTTP requests, define routes, and manage middleware. It also enables communication between the client (front-end) and server (back-end) through APIs
    • Express, like many others, generally uses JSON for data exchange and implements REST APIs to handle client-server communication. This generally allows for the above mentioned stateless way of communication between both ends of the application
    • A web server would do things lie handle the client requests and handle buisness logic like interacting with databases
    • A middleware function in Express can help with processing requests and reponses in the express environment
    • A route is a part of the code that associates an HTTP request, such as GET, POST, or DELETE with a URL and the function that gets called that handles the URL.
    • Basically the app.get or app.post(/login/api, (res, req) => {}) ordeal that you might see, with the function you define at what happens whenever that URL is called into Express
    • This makes it good for splitting an application’s user interface based on rules identified by the browser’s own URL without a lot of the regular Node hassle
    • Router Functions are called middleware collectively. Middleware is responsible for responding to an HTTP request or calling another function the middleware chain.
    • Express handles router functions through the Router Class such as Router.get(), which can handle the HTTP GET requests as the name suggests. With other router functions existing like Router.post(), Router.put(), and Router.delete, which all take in the same URL path and a callback function whenever the process is done
    • In addition to routing, middleware is also responsible for providing secure connections among services by encrypting and decrypting data, managing application loads by distributing traffic to different servers, and sorting or filtering data before the data is returned to the client
  • Routing, Middleware, and Templating:
    • Routing is a very important concept in back-end development, where in which client-side requests are generally directed to different places via routes which are in some cases just different /route/to/here inside of the URL
    • Common routing requests include GET, POST, PUT, & DELETE
    • The server must handle appropriate requests to each of the given routes, or return the appropriate error message
    • Routing can be handled both inside of the Application Level and the Router Level
    • Pasted image 20260823193944.png
    • The above hand code uses Express in order to handle routing to the user/about/:id route, and for each one of the given requests, you have a res.send() function which gives back the response to the use, which in this case kind of just print out the ID of the params for each of the different POST, GET requests
    • This is kind of just the basic way to route applications level
    • Pasted image 20260823194202.png
    • As for routing with Routers these are new objects you define using the let routername = express.Router(); method, which is then assigned a conjunction of a base path so you do not need to specify the whole entire route inside of your GET or POST request
    • Instead, you just use the variable holding the router object that you made, which stores the pre-made path, and this lets you access it from that starting point
    • This is good for when you have a lot of diverging pathways and want to keep things a bit more in line
    • Middleware are functions that have access to the request and response objects and the next function, they basically stand between the outgoing and forth coming data that you have in the back-end, and are able to perform different operations on it
    • They can be chained, with one middleware function calling another or them basically going in order
    • They are generally categorizes based on purpose, use, and source, with 5 common types being router level, application level, built in, error handling, and built in
    • Generally middleware is user good for things like authentication, error handling, and parsing requests
    • Pasted image 20260823194800.png
    • Application Level Middleware is bound to a given application with the app.use() function, and can be written from scratch using the javascript arrow syntax, or can be some other third-party function and what not as well.
    • As previously said, this makes it easy to interpret and authentication data because ALL data is routed in through this middleware
    • In the above hand code, this is a password checking function that checks to see if you have the correct password
    • Kind of like a gate keeper, and determines what gets sent over to the server and what gets stopped at the door
    • Pasted image 20260823194952.png
    • Router-level middleware is bound with router.use(), and is NOT bound to the application, but is instead bound to a single instance of that given router, which is very useful if you want to have different levels of authorization based on the different routes that you might end up taking
    • Pasted image 20260823195200.png
    • Error handling middleware can be bound with either app.use() or router.use(), it always takes in at least FOUR args, which are error, req, res, and the next function it needs to be changed to
    • Even if you do not actually use the ext parameter, you still actually have to define it in the method signature
    • In the above hand code, if the user that is trying to be accessed is equal to 1, then that user is an admin and an error is thrown, otherwise, the user is accepted in a seamless manner
    • The code seems to run in a sequential manner, so the next() function refers to the actual next method that is defined inside of the code, so in the above hand example, when a request is made to /user/:id you first check if the ID value is one, and if so you “throw an error” which makes the error object not null
    • Then inside of the next actual function which has the error code, you check to see if error is null, and if not then you send back the error, if it is null, you move on to the next function to accept the user
    • THE CODE STILL RUNS LINE BY LINE SORT OF, I THINK THAT IS IMPORTANT
    • Pasted image 20260823195931.png
    • Built-in Middleware is anything like static files, cookie parser, or json, and as the name suggest are generally built into the application that you are using, or the modules you are using. Basically built into Express itself or other such things, you can even create your own if you would like.
    • It can also be specifically bound to the router or app
    • It is generally also used for things like say parsing JSON input from the front-end or rendering out HTML code or generally other things like that
  • Authentication and Authorization in Node.js:
    • See IT Security - Defense Against The Digital Dark Arts series from the Google IT cert to see why authorization and security are important inside of any real application or service, I won’t rehash all of that here

    • See specifically ISDADDA - Module 3 - The 3 A's of Cybersecurity- Authentication, Authorization, Accounting

    • Authentication is basically verifying a user’s identity by using their credentials, like certs, passwords, all that jazz to see that they are who they say they are

    • This is good because it makes sure that only authorized users are able to access the system, and it is the job of the backend to handle authentication

    • Three Popular Authentication Methods in Node (and really anywhere else)

      • Pasted image 20260823200627.png

      • Session Based you log in with your credentials which are stored inside of a database that the things that you type in are checked against, if valid, the server creates a unique Session ID that is stored in the database and browser cookies, when logging out, or after a certain period, the session ID is destroyed and the logout is expired

      • Token Based - this basically involves both authentication and authorization, the first portion is when you get a token that basically identifies you as who you are, and then the second bit is when that given token is checked to allow you to access the resources you wish to access, denying the ones you cannot access

      • Tokens contain THREE parts

        • Header - the token type and the algorithm used to generate it
        • Payload - the user attributes and things like the expiration times of the token and session
        • Signature - the portion that basically protects the token in transit so you know if it gets tampered with
      • TOKEN BASED AUTHENTICATION:

      • JwT (pronounce Jot) - is an internet standard for creating JSON payload data

      • Inside of a given token-based authentication set up, your browser calls an authentication server, which provides access to the given web application.

      • The given authentication server associated with the web app gives you an ID token, which is store as a secure cookie in the client

      • This token is then passed to the web app server, which provides authentication and allows you to enter

      • Pasted image 20260823201257.png

      • TOKEN BASED AUTHORIZATION:

      • This occurs whenever a client tries to get access to a protected unauthorized resources, such as an API or something else that is protected

      • Then, an authorization token, separate from the ID token is created, which is sent back over to the server and stored

      • Then, which HTTP request, that token is passed over to a resource server, where in which it is validated to see if you have the permission to access what it is that you are trying to access

      • Token encryption is generally used for protection of user credentials, again see IT Security - Defense Against The Digital Dark Arts for more details

      • Pasted image 20260823201541.png

      • Pasted image 20260823201553.png

      • Passwordless Based this eliminates the need for traditional passwords, and uses things like biometrics, magic links, or one-time passcodes

      • These are then used to authentication you, and it uses the asymmetric model of public/private key encryption for security, and since this is generally pretty expensive computationally, it is used for things like password recovery systems most often

    • Example of Session based authentication

    const express = require('express');
    const session = require('express-session');
    const app = express();
     
    // Middleware to set up session management
    app.use(session({
     
    secret: 'secret-key', // Replace with a strong secret key
    resave: false, // Whether to save the session data if there were no modifications
    saveUninitialized: true, // Whether to save new but not modified sessions
    cookie: { secure: false } // Set to true in production with HTTPS
     
    }));
     
     
    // POST endpoint for handling login
    app.post('/login', (req, res) => {
     
    const { username, password } = req.body;
     
    // Simulated user authentication (replace with actual logic)
    if (username === 'user' && password === 'password') 
    {
    	req.session.user = username; // Store user information in session
    	res.send('Logged in successfully');
    } 
    else 
    {
    	res.send('Invalid credentials');
    }
    });
     
      
     
    // GET endpoint for accessing dashboard
    app.get('/dashboard', (req, res) => {
     
    if (req.session.user) 
    {
    res.send(`Welcome ${req.session.user}`); // Display welcome message with user's name
    } 
    else {
    res.send('Please log in first');
    }
     
    });
     
     
    // Start the server on port 3000
    app.listen(3000, () => console.log('Server running on port 3000'));
    • Example of Token based authentication
    const express = require('express');
    const jwt = require('jsonwebtoken');
    const bodyParser = require('body-parser');
     
      
    const app = express();
    app.use(bodyParser.json());
    const secretKey = 'your-secret-key'; // Replace with a strong secret key
     
      
     
    // POST endpoint for user login and JWT generation
    app.post('/login', (req, res) => {
     
    const { username, password } = req.body;  
     
    // Simulated user authentication
    if (username === 'user' && password === 'password') 
    {
     
    // Generate JWT with username payload
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
    res.json({ token }); // Send token as JSON response
     
    } 
    else 
    {
    res.send('Invalid credentials');
    }
     
    });
     
    // GET endpoint to access protected resource (dashboard)
    app.get('/dashboard', (req, res) => {
     
    // Get token from Authorization header
    const token = req.headers['authorization'];
     
    if (token) 
    {
     
    // Verify JWT token
    jwt.verify(token, secretKey, (err, decoded) => {
     
    if (err) 
    {
    res.send('Invalid token');
    }
    else 
    {
    // Token is valid, send welcome message with username
    res.send(`Welcome ${decoded.username}`);
    }
    });
     
     
    } 
    else 
    {
    res.send('Token missing');
    }
     
    });
     
    // Start server
    app.listen(3000, () => console.log('Server running on port 3000'));
    • Password / Asymmetric Verification
    const express = require('express');
    const bodyParser = require('body-parser');
    const nodemailer = require('nodemailer');
     
    const app = express();
    app.use(bodyParser.json());
    const users = {}; // In-memory storage for demo purposes
     
    // Endpoint to request access and send verification code via email
    app.post('/request-access', (req, res) => {
    const { email } = req.body;
     
    // Generate a 6-digit verification code
    const code = Math.floor(100000 + Math.random() * 900000).toString();
     
    // Store the code in memory (users object)
    users[email] = code;
     
    // Simulated email sending (for demonstration)
    console.log(`Sending code ${code} to ${email}`);
    res.send('Code sent to your email');
    });
     
     
    // Endpoint to verify the received code
    app.post('/verify-code', (req, res) => {
    const { email, code } = req.body;
     
    // Compare the received code with stored code for the email
    if (users[email] === code) 
    {
    // Code matches, access granted
    res.send('Access granted');
    } 
    else
    {
    //Code does not match, access denied
    res.send('Invalid code');
    }
    });  
     
    // Start the Express server
    app.listen(3000, () => console.log('Server running on port 3000'));
  • HTTP Methods and Rest APIs:
    • Token-Based authentication is generally the most popular method as it seems because it is VERY scalable, because the token only really needs to be stored on the client side
    • The server only needs to verify the token alongside the user information, and so it is easier to authenticate multiple users
    • It is very flexible because you can use them across multiple servers and across more sites as well
    • It is also VERY secure because you can encrypt tokens too
    • In the images below is depicted a process where in which Authentication is done with Express API server, where in which a POST request for logging in will return a web token for signing in by sending the username and password ordeal over to a signin/ endpoint
    • Then, a second GET API will be a way to get employee information that is ONLY FOR AUTHORIZED EMPLOYEES from the employee/ endpoint
    • Pasted image 20260823202837.png
    • Pasted image 20260823202935.png
    • Pasted image 20260823202957.png
    • Pasted image 20260823203019.png
    • Pasted image 20260823203030.png
    • Pasted image 20260823203115.png
    • Pasted image 20260823203151.png
    • Pasted image 20260823203227.png
  • Express Best Practices:
    • Web framework Directory Structures things like Ruby on Rails or Django all have their own required directory structures

    • Express however does not require a particular directory structure however, there are still caveats as there are general good practices to follow when designing your own

    • The following folders and conventionally used to store files

    • Project Folder

      • node_modules
        • This holds all of the applications modules, packages, and their dependencies
        • It is automatically created after just running npm install
      • config
        • This should contain configuration files such as
        • Database connection configuration
        • Environment variables
        • Credentials file including API keys for external services
      • models
        • This should contain the data models for the application
        • The data models would specify the type of data store defined by an ORM (object relational mapping) library
      • routes
        • This is used to specify all of the routes for all the entities in different files
        • It should have one file for each logical set of routes that branch off and what not, so like a file for items/ and users/ for example I think
      • views
        • This should contain things like template files
        • These templates dynamically write HTML, CSS, and JS for the client
        • Making it easy to generate user-specific user interfaces
      • public
        • This would contain all of the static content inside of your application, such as images, CSS, and JS
        • It is generally helpful to have a sub folder for each of those items as well
    • Also inside of your project folder

      • app.js- This is the MAIN CONFIGURATION file for your application, this imports the single module that has all of the routes that come from the routes. js module, and is also where the logic for the app happens I am sure
      • routes.js- this is a central location where you can access all of the routes inside of your application, and this is where all of the files from the routes folder mentioned above are imported into
      • package.json- this specifies the needed metadata that you would need for the managing the project dependencies
    • API Directory Structure, very similar to that of the above hand structure, except for the fact that there is no Views or Public folder

    • Naming routes- use a noun whenever you are trying to give an identifier, inside of the table there are things like common methods and routes for an application

    • Pasted image 20260823204502.png

    • Pasted image 20260823204519.png

    • Pasted image 20260823204624.png

    • HTTP status codes as well with the table defined out better inside of references as well for easier search in obsidian

  • Module Summary:
    • Developers rely on third-party packages to extend Node.js. 
    • You can use the npm application to manage Node.js packages in your Node.js framework installation.
    • The MVC architecture style divides a back-end application into three parts: the model, the view, and the controller.
    • REST API frameworks use HTTP methods to communicate with each other.
    • Express abstracts low-level details. 
    • Routing can be handled at the application level or at the router level. 
    • Five types of middleware are application level, router level, error handling, built-in middleware, and third party. 
    • Template rendering is the ability of the server to fill in dynamic content. 
    • The npm jsonwebtoken package should be required in an Express application to authenticate a user.

==Glossary

TermDefinition
Access TokenA small piece of code that contains information about the user, their permissions, groups, and expirations that get passed from a server to the client.
API EndpointThe touchpoint where the API connects to the application it is communicating with.
Application-Level MiddlewareActs as a gatekeeper and is bound to the application. No request to the application server can go past it.
AuthenticationThe process of confirming a user’s identity using credentials by validating who they claim to be. Authentication assures an application’s security by guaranteeing that only those with valid credentials can access the system.
AuthorizationIn token-based authentication, it is the process that gets executed when a web application wants to access a protected resource. A user authenticates against an authorization server.
Built-In MiddlewareCan be bound to either the entire application or to specific routers. Useful for activities such as rendering HTML pages from the server, parsing JSON input from the front end, and parsing cookies.
ControllerThe layer in an MVC application regulates the flow of the data. It is responsible for processing the data supplied to it by the user and sends that data to the model for manipulation or storage.
Error-Handling MiddlewareCan be bound to either the entire application or to specific routers. Error-handling middleware always takes four arguments: error, request, response, and the next function that it needs to be chained to. Even if you don’t use the next parameter, you still define it in the method signature.
Express.jsA web application framework based on the Node.js runtime environment, however, Express abstracts low-level details.
FrameworkA framework is a skeleton on which an application is built for a specific environment. The framework is the fundamental structure that supports the application.
HTTP HeadersAdditional information about and contained in an HTTP response or request.
HTTP RequestA method called by a client and sent to a server requesting access to a resource on the server.
HTTP ResponseA method called by a server and sent to a client in response to an HTTP request.
ID TokenAn artifact that proves that a user has been authenticated and contains information about authorized API routes.
JSON PayloadData that is transferred in JSON format between the client and server in the header of an HTTP method.
JWTA JSON Web token. An internet standard for creating encrypted payload data in JSON format.
MiddlewareIncludes functions that have access to the request and response objects and the next() function.
ModelThe layer in an MVC application responsible for managing the data of the application. It interacts with the database and handles the data logic.
MVCShort for “Model-View-Controller”. It is an architectural pattern that divides an application into three components: model, view, and controller.
Node FrameworkA framework that works in conjunction with Node.js. A framework is a skeleton on which an application is built for a specific environment. The framework is the fundamental structure that supports the application.
npmAn application that manages Node.js packages in your Node.js framework installation.
Passwordless AuthenticationA type of authentication that uses public/private key pairs to encrypt and decrypt data passed between client and server without the need for a password.
Private KeyIn cryptography, it is a key that is known only to a specific client used to decrypt messages. Used in conjunction with a public key.
Public KeyIn cryptography, it is a key that can be used by anyone to encrypt messages for a specific client. Used in conjunction with a private key.
REST“Representational state transfer” is a set of guidelines for creating stateless client/server interfaces using HTTP methods.
REST APIAn API used for communicating between clients and servers that conforms to REST architecture principles.
RouteThe code that associates an HTTP request method and a URL.
Router-Level MiddlewareBound to a router and not bound to an application. You can use specific middleware for a specific route instead of having all requests go through the same middleware. Then you bind the application routes to each router.
Session-based AuthenticationA type of authentication where a user provides login credentials that are verified against stored credentials in a database on a server. A session ID is provided to the client and stored in the browser as a cookie.
StatelessnessImplies that each HTTP request happens in isolation in relation to other requests. The state of the client is not stored on the server; the state is passed to the server by the client for each request.
Template RenderingThe ability of the server to fill in dynamic content in an HTML template.
TokenContains three parts, the header, the payload, and the signature. The header contains information about the type of token and the algorithm used to create it. The payload contains user attributes, called claims, such as permissions, groups, and expirations. The signature verifies the token’s integrity, meaning that the token hasn’t changed during transit.
Token-based AuthenticationA type of authentication that uses access tokens, often JWTs, which get passed between server and client with the data that is passed between the two.
TypeScriptA language that builds on top of JavaScript and provides type safety which assists with the development of large-scale applications by reducing the complexity of component development in JavaScript.
ViewThe layer in an MVC application responsible for rendering the presentation of the data that is passed to it by the model.
xml2jsNode.js package to parse a string of XML elements into a JavaScript object.

==Cheat Sheet

Package/MethodDescriptionCode Example
Dependencies in package.jsonA dependency of express version between 4.0 to 5.0 will be declared as:plaintext
”dependencies”:{“express”:“4.x”}
new express()Creates an express object which acts as a server application.javascript
const express = require(“express”);
const app = new express();
express.listen()The listen method is invoked on the express object with the port number on which the server listens. The function is executed when the server starts listening.javascript
app.listen(3333, () => {
console.log(“Listening at http://localhost:3333”)
})
express.get();This method is meant to serve the retrieve requests to the server. The get() method is to be implemented with two parameters; the first parameter defining the endpoint and the second parameter is a function taking the request-handler and response-handler.javascript
// handles GET queries to end point /user/about/id.
app.get(“user/about/:id”, (req,res)=>{
res.send(“Response about user ” +req.params.id)
})
express.post();This method is meant to serve the create requests to the server. The post() method is to be implemented with two parameters: the first parameter defines the end-point and the second parameter is a function taking the request-handler and response-handler.javascript
// handles POST queries to the same end point.
app.post(“user/about/:id”, (req,res)=>{
res.send(“Response about user ” +req.params.id)
})
express.use()This method takes middleware as a parameter. Middleware acts as a gatekeeper in the same order that it is used, before the request reaches the get() and post() handlers. The order in which the middleware is chained depends on the order in which the .use() method is used to bind them. The middleware myLogger() function takes three parameters, which are request, response, and next. You can define a method that takes these three parameters and then bind it with express.use() or router.use(). Here, you are creating middleware named myLogger and making the application use it. The output rendered includes the time the request is received.javascript
const express = require(“express”);
const app = new express();

function myLogger(req, res, next){
req.timeReceived = Date();
next();
}

app.use(myLogger);

app.get(”/”, (req, res)=>{
res.send(“Request received at “+req.timeReceived+” is a success!”)
})
express.Router()Router-level middleware is not bound to the application. Instead, it is bound to an instance of express.Router(). You can use specific middleware for a specific route instead of having all requests going through the same middleware. Here, the route is /user and you want the request to go through the user router. Define the router, define the middleware function that the router will use and what happens next, and then you bind the application route to the router.javascript
const express = require(“express”);
const app = new express();

let userRouter = express.Router();
let itemRouter = express.Router();

userRouter.use(function (req, res, next){
console.log(“User query time:”, Date());
next();
})

userRouter.get(”/:id”, function (req, res, next) {
res.send(“User “+req.params.id+ ” last successful login “+Date())
})

app.use(“/user”, userRouter);

app.listen(3333, () => {
console.log(“Listening at http://localhost:3333”)
})
express.static()This is an example of static middleware that is used to render static HTML pages and the images from the server side. At the application level, the static files can be rendered from the cad220_staticfiles directory. Notice that the URL has only the server address and the port number followed by the filename.javascript
const express = require(“express”);
const app = new express();

app.use(express.static(“cad220_staticfiles”))

app.listen(3333, () => {
console.log(“Listening at http://localhost:3333”)
})
jsonwebtoken.sign()Used for signing-in based on a generated JWT (JSON Web token)javascript
if (uname = “user” && pwd = “password”) {
return res.json({
token: jsonwebtoken.sign({ user: “user” }, JWT_SECRET),
});
}
jsonwebtoken.verify()Verifies a JWT by passing the token value & the JWT secret as arguments.javascript
const verificationStatus = jsonwebtoken.verify(tokenValue, “aVeryVerySecretString”);
Project folder strucureA fairly established project structure for API’s built using Express.js is:plaintext
test-project/
node_modules/
config/
db.js //Database connection and configuration
credentials.js //Passwords/API keys for external services used by your app
models/ //For mongoose schemas
items.js
prices.js
routes/ //All routes for different entities in different files
items.js
prices.js
app.js
routes.js //Require all routes in this and then require this file in package.json

References

REST APIs have the following characteristics:

  • Resource-based; that is, they describe sets of resources
  • Only contain nouns, not verbs
  • Use singular nouns when referring to a singular resource or plural nouns when referring to a collection of resources
  • Always identified by URLs

NOT RESTful APIs vs RESTful equivalents

NOT RESTful APIsRESTful equivalents
GET http://api.myapp.com/getUser/123GET http://api.myapp.com/users/123
POST http://api.myapp.com/addUserPOST http://api.myapp.com/users
GET http://api.myapp.com/removeUser/123DELETE http://api.myapp.com/users/123
Status Code RangeMeaning
200-299Everything is OK
300-399Resource has moved
400-499Client-side error
500-599Server-side error

For finding out how to document shit:
API Blueprint
Swagger