Basic Node and Express Flashcards
Create express app object(requiring express module & calling express function)
-npm install express
-const express = require(‘express’);
-const app = express();
Structure for routes in express
app.METHOD(PATH(server-relative),HANDLER);
Types of Methods
GET, POST, PUT, DELETE, OPTIONS, LISTEN, HEAD
What is PATH
A URL pattern or endpoint relative to the server’s domain where the handler function should be executed
What is Handler
A function handling the route when a specific route is matched during incoming HTTP request
What form does the handler take
function(request, response){…}
What do route handlers do?
Provide the core functionality for defining the behavior of your web application’s endpoints
Give example of where route handler goes:
app.get(‘/endpoint’, function(req, res) {
//route handler here
res.send(‘this is the endpoint route’)
});
What are 2 ways to Serve a HTML file:
-express.static middleware
-res.sendFile() METHOD
Show how to serve static files from a directory(e.g ‘public’)
app.use(express.static(‘public’));
When is express.static used
serving multiple static files(e.g HTML, CSS, Javascript)
Show route handler for serving an HTML file with res.sendFile():
app.get(‘/page’, function(req, res){
res.sendFile(__dirname + ‘/public/page.html’);
});
‘/page’ = desired route path
‘/public/page.html’ = file relative to your project directory
When to use res.sendFile()
Useful for serving specific files or for adding additional logic before sending the files
What are middlewares?
-is software logic that intercepts and processes HTTP requests and responses within the application’s request-response cycle. It can modify request and response objects, execute additional code, or terminate the request cycle.
-Are functions that intercept route handlers, adding some kind of information.
-Has access to the request object(‘req’), the response object(‘res’), and the next middleware function in the application’s request-response cycle.
-Can execute code, make changes to the request and response objects, end the request-response cycle, or call the next middlewware function.
what method does middlewares need to be mounted on?
app.use(…);
Show how middleware would be executed for a certain request:
app.use(path, middlewareFunction)
Show how middleware will be executed for all requests:
app.use(middlewareFunction)
Common directory names for static assets:
‘public’, ‘static’, ‘assets’
How to access static assets in the browser, assuming your server is running on port 3000:
http://localhost:3000/index.html
What does JSON stand for?
Javascript Object Notation
Why is JSON commonly used in web development?
-Transmitting data between a server and a web application.
-Easy for machines to parse and generate JSON data.
-Popular due to its simplicity, readability, and flexibility.
What does REST API stand for?
Representational State Transfer Application Programming Interface
What does a REST API do?
Play a crucial role in modern web development by enabling diverse applications to communicate and share data over the web in a flexible, efficient, and straightforward manner.
Serve JSON on a specific route(create route handler that sends JSON data as the response):
app.get(‘/data’, function(req, res){
const jsonData = {
message: “Hello World”,
numbers: [1, 2, 3, 4, 5]
};
res.json(jsonData);
});
What is an .env file?
Configuration file commonly used in Node.js and other server-side applications to manage environment variables
In .env, what are enviroment variables?
-Are key-value pairs that define the enviroment in which your application runs.
-Contains sensitive information such API keys, database credentials, or configurations settings.
Example of enviroment variables in your .env file:
-PORT=3000
-DATABASE_URL=mongodb://localhost:27017/mydatabase
-API_KEY=your_api_key_here
How do you access enviroment variables in your application & show how to access a PORT variable ?
-use the ‘process.env’ object,
-const port = process.env.PORT
How do you load the .env file to make the enviroment variables available?
-with a package like ‘dotenv’
-npm install dotenv
Once dotenv is installed, what do you add on the top line of your application file?
require(‘dotenv’).config();
What is a root-level request logger middleware?
-is middleware that captures and logs incoming HTTP requests at the topmost level of the application’s middleware stack.
-Powerful tool for enhancing the observability, security, and manageability of web applications.
-Gives valuable insights into the application’s usage and behavior, which can aid in debugging, monitoring, and optimizing the application.
-Function that logs information about each incoming request to the server, regardless of the route or endpoint being accessed.
Create a middleware function that implements a root-level logger:
app.use((req, res, next) => {
console.log(${new Date().toISOString()} - ${req.method} request to ${req.url}
);
next(); // Pass control to the next middleware function
});
What is the purpose of chaining middleware?
- Modularization and Reusability: Chaining middleware enables developers to modularize and reuse code for common tasks like authentication, logging, and error handling.
- Sequential Processing: Middleware functions are executed in a specified order, allowing developers to control the flow of request handling and implement complex logic step by step.
- Granular Control: Developers can apply different middleware to specific routes or groups of routes, ensuring that each middleware function is applied precisely where needed.
- Error Handling: Chaining error-handling middleware at the end of the stack centralizes error management and ensures consistent handling of errors across the application.
- Extensibility and Customization: Middleware chaining offers flexibility to extend or modify application behavior by adding, removing, or reordering middleware functions as needed.
Chain middleware to create a time server:
app.get(‘/now’, (req, res, next) => {
req.time = new Date().toString()
next()
}, (req, res) => {
res.json({time: req.time})
});
What is a route parameter?
-A route parameter is a dynamic part of a URL path that is used to capture variable values, a piece of data, specified by the client when making a request to the server.
-Route parameters are specified in the route path definition and are denoted by a colon (:
) followed by the parameter name.
How do you access a route parameter input
with req.params in the route handler function
Show an example how a route parameter input looks and how to access them:
app.get(‘/users/:userId’, function(req, res) {
const userId = req.params.userId;
res.send(`User Id: ${userId}`); });
What is a query parameter?
-is a component of a URL that is used to provide additional information to a web server when making a request.
-Query parameters are typically appended to the end of a URL following a question mark ? and are structured as key-value pairs separated by an ampersand &.
What does a query parameter look like?
http://url/search?q=term&page=2
How do you access a query parameter from the client in an express.js application?
through the ‘req.query’ object in the route handler
Show an example of one accessing a query parameter from the client:
app.get(‘/search’, (req, res) => {
const qQuery = req.query.q;
const page = req.query.page;
res.send(`Query: ${qQuery}, Page: ${page}`); });
What is express.json?
-is a built-in middleware function in Express.js, a popular web application framework for Node.js.
-It is used to parse incoming request bodies with JSON payloads.
-express.json() middleware parses this JSON data and makes it available in the req.body property of the request object.’
How can one use express.json in an express.js application?
app.use(express.json());
How to access form data thats submitted:
app.post(‘/submit’, function(req, res){
const formData = req.body;
res.json(formData); });
What is app.listen()?
its a method that starts a server and listens for incoming requests on a specified port
What is app.use()?
-a method that mounts middleware functions at a specified path.
-It is used to configure middleware for handling requests.
What are app.get(), app.post(), app.put(), app.delete()?
are methods that define routes for specefic HTTP methods(GET, POST, PUT, DELETE) and specify the handler functions to be executed when the server receives requests for those routes.
What is app.all()?
a method similar to the HTTP method-specific routing methods, but it matches all HTTP methods.
What is app.route()?
a method that creates a chainable route handler for a specific route.
What is app.set()?
a method that sets application settings, which can be retrieved using app.get().
What is GET route for the home page? Ex?
-This route serves the home oage of your application.
-Ex.
app.get(‘/’, function(req, res){…});
What is GET route for? Ex?
-These routes serve specific resources or data from your express.application.
-Ex.
app.get(/users, function(req, res) {…});
What is POST route for submission? Ex?
-This route handles form submissions from the client.
-Ex.
app.post(‘/submit’, function(req, res){…});
What is PUT route used for? Ex?
-This route updates existing resources in your application.
-Ex.
app.put(‘users/:id’, function(req, res){…});
What is DELETE route used for? Ex?
-This route deletes resources from your application.
-Ex.
app.delete(‘/users/:id’, function(req, res){…});
What is Error-handling routes? Ex?
-These routes handle errors that occur during the request-response cycle.
-Ex.
app.use(function(err, req, res, next){…});
What are Middleware routes? Ex?
-These routes use middleware functions to perform tasks such as authentication, logging, or data validaton.
-Ex.
app.use(function(req, res, next){…});
What is Helmet? How do you use it?
-is a middleware for securing express apps by settings various HTP headers to protect against common vulerabilites, such as XSS (Cross-Site Scripting), Clickjacking, and others.
-Ex.
const helmet = require(‘helmet’);
app.use(helmet());
What is Compression? How do you use it?
-is a middleware used to compress HTTP responses, reducing the size of data sent over the network and improving the performance of web applications.
-Ex.
const compression = require(‘compression’);
app.use(compression());
What is Cookie Parser? How do you use it?
-is a middleware used to parse cookies attached to the client request. It makes cooke data available under ‘req.cookies’.
-Ex.
const cookieParser = require(‘cookie-parser’);
app.use(cookieParser());
What is Cors? How do you use it?
is a middleware used to enable Cross-Origin Resource Sharing (CORS) in express applications, allowing controlled access to resources from different domains.
What is Passport.js? How do you use it?
-is primarily known as an authentication library
-it also provides middleware functions that can be used in an Express application’s middleware stack to handle authentication-related tasks, making it a middleware in the context of Express.
Ex.
const passport = require(‘passport’);
// Set up Passport middleware for authentication
app.use(passport.initialize());
app.use(passport.session()); // If using session-based authentication
What is Express-validator? How do you use it?
-is specifically designed as middleware for request validation in Express applications.
-It intercepts incoming requests, validates them according to defined rules, and can sanitize the data before passing it along to the route handlers.
Ex.
const { body, validationResult } = require(‘express-validator’);
// Middleware for validating request body using Express-validator
app.post(‘/user’, [
body(‘username’).isEmail(),
body(‘password’).isLength({ min: 5 }),
], (req, res) => {
// Handle request and access validation results using validationResult
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Proceed with handling the valid request
});
What is Connect-flash? How do you use it?
-is middleware used for managing temporary messages in Express applications.
-It allows for storing and displaying flash messages to users between requests, making it part of the middleware stack in an Express app.
Ex.
const flash = require(‘connect-flash’);
// Set up session middleware
app.use(session({
secret: ‘secret’,
resave: false,
saveUninitialized: true
}));
// Initialize and use Connect-flash for flash messages
app.use(flash());