Basic Node and Express Flashcards

1
Q

Create express app object(requiring express module & calling express function)

A

-npm install express
-const express = require(‘express’);
-const app = express();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Structure for routes in express

A

app.METHOD(PATH(server-relative),HANDLER);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Types of Methods

A

GET, POST, PUT, DELETE, OPTIONS, LISTEN, HEAD

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is PATH

A

A URL pattern or endpoint relative to the server’s domain where the handler function should be executed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Handler

A

A function handling the route when a specific route is matched during incoming HTTP request

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What form does the handler take

A

function(request, response){…}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What do route handlers do?

A

Provide the core functionality for defining the behavior of your web application’s endpoints

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Give example of where route handler goes:

A

app.get(‘/endpoint’, function(req, res) {
//route handler here
res.send(‘this is the endpoint route’)
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are 2 ways to Serve a HTML file:

A

-express.static middleware
-res.sendFile() METHOD

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Show how to serve static files from a directory(e.g ‘public’)

A

app.use(express.static(‘public’));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When is express.static used

A

serving multiple static files(e.g HTML, CSS, Javascript)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Show route handler for serving an HTML file with res.sendFile():

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

When to use res.sendFile()

A

Useful for serving specific files or for adding additional logic before sending the files

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are middlewares?

A

-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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

what method does middlewares need to be mounted on?

A

app.use(…);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Show how middleware would be executed for a certain request:

A

app.use(path, middlewareFunction)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Show how middleware will be executed for all requests:

A

app.use(middlewareFunction)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Common directory names for static assets:

A

‘public’, ‘static’, ‘assets’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to access static assets in the browser, assuming your server is running on port 3000:

A

http://localhost:3000/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does JSON stand for?

A

Javascript Object Notation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why is JSON commonly used in web development?

A

-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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does REST API stand for?

A

Representational State Transfer Application Programming Interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does a REST API do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Serve JSON on a specific route(create route handler that sends JSON data as the response):

A

app.get(‘/data’, function(req, res){
const jsonData = {
message: “Hello World”,
numbers: [1, 2, 3, 4, 5]
};
res.json(jsonData);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is an .env file?

A

Configuration file commonly used in Node.js and other server-side applications to manage environment variables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

In .env, what are enviroment variables?

A

-Are key-value pairs that define the enviroment in which your application runs.
-Contains sensitive information such API keys, database credentials, or configurations settings.

27
Q

Example of enviroment variables in your .env file:

A

-PORT=3000
-DATABASE_URL=mongodb://localhost:27017/mydatabase
-API_KEY=your_api_key_here

28
Q

How do you access enviroment variables in your application & show how to access a PORT variable ?

A

-use the ‘process.env’ object,
-const port = process.env.PORT

29
Q

How do you load the .env file to make the enviroment variables available?

A

-with a package like ‘dotenv’
-npm install dotenv

30
Q

Once dotenv is installed, what do you add on the top line of your application file?

A

require(‘dotenv’).config();

31
Q

What is a root-level request logger middleware?

A

-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.

32
Q

Create a middleware function that implements a root-level logger:

A

app.use((req, res, next) => {
console.log(${new Date().toISOString()} - ${req.method} request to ${req.url});
next(); // Pass control to the next middleware function
});

33
Q

What is the purpose of chaining middleware?

A
  1. Modularization and Reusability: Chaining middleware enables developers to modularize and reuse code for common tasks like authentication, logging, and error handling.
  2. 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.
  3. Granular Control: Developers can apply different middleware to specific routes or groups of routes, ensuring that each middleware function is applied precisely where needed.
  4. Error Handling: Chaining error-handling middleware at the end of the stack centralizes error management and ensures consistent handling of errors across the application.
  5. Extensibility and Customization: Middleware chaining offers flexibility to extend or modify application behavior by adding, removing, or reordering middleware functions as needed.
34
Q

Chain middleware to create a time server:

A

app.get(‘/now’, (req, res, next) => {
req.time = new Date().toString()
next()
}, (req, res) => {
res.json({time: req.time})
});

35
Q

What is a route parameter?

A

-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.

36
Q

How do you access a route parameter input

A

with req.params in the route handler function

37
Q

Show an example how a route parameter input looks and how to access them:

A

app.get(‘/users/:userId’, function(req, res) {
const userId = req.params.userId;

res.send(`User Id: ${userId}`); });
38
Q

What is a query parameter?

A

-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 &.

39
Q

What does a query parameter look like?

A

http://url/search?q=term&page=2

40
Q

How do you access a query parameter from the client in an express.js application?

A

through the ‘req.query’ object in the route handler

41
Q

Show an example of one accessing a query parameter from the client:

A

app.get(‘/search’, (req, res) => {
const qQuery = req.query.q;
const page = req.query.page;

res.send(`Query: ${qQuery}, Page: ${page}`); });
42
Q

What is express.json?

A

-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.’

43
Q

How can one use express.json in an express.js application?

A

app.use(express.json());

44
Q

How to access form data thats submitted:

A

app.post(‘/submit’, function(req, res){
const formData = req.body;

res.json(formData); });
45
Q

What is app.listen()?

A

its a method that starts a server and listens for incoming requests on a specified port

46
Q

What is app.use()?

A

-a method that mounts middleware functions at a specified path.
-It is used to configure middleware for handling requests.

47
Q

What are app.get(), app.post(), app.put(), app.delete()?

A

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.

48
Q

What is app.all()?

A

a method similar to the HTTP method-specific routing methods, but it matches all HTTP methods.

49
Q

What is app.route()?

A

a method that creates a chainable route handler for a specific route.

50
Q

What is app.set()?

A

a method that sets application settings, which can be retrieved using app.get().

51
Q

What is GET route for the home page? Ex?

A

-This route serves the home oage of your application.
-Ex.
app.get(‘/’, function(req, res){…});

52
Q

What is GET route for? Ex?

A

-These routes serve specific resources or data from your express.application.
-Ex.
app.get(/users, function(req, res) {…});

53
Q

What is POST route for submission? Ex?

A

-This route handles form submissions from the client.
-Ex.
app.post(‘/submit’, function(req, res){…});

54
Q

What is PUT route used for? Ex?

A

-This route updates existing resources in your application.
-Ex.
app.put(‘users/:id’, function(req, res){…});

55
Q

What is DELETE route used for? Ex?

A

-This route deletes resources from your application.
-Ex.
app.delete(‘/users/:id’, function(req, res){…});

56
Q

What is Error-handling routes? Ex?

A

-These routes handle errors that occur during the request-response cycle.
-Ex.
app.use(function(err, req, res, next){…});

57
Q

What are Middleware routes? Ex?

A

-These routes use middleware functions to perform tasks such as authentication, logging, or data validaton.
-Ex.
app.use(function(req, res, next){…});

58
Q

What is Helmet? How do you use it?

A

-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());

59
Q

What is Compression? How do you use it?

A

-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());

60
Q

What is Cookie Parser? How do you use it?

A

-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());

61
Q

What is Cors? How do you use it?

A

is a middleware used to enable Cross-Origin Resource Sharing (CORS) in express applications, allowing controlled access to resources from different domains.

62
Q

What is Passport.js? How do you use it?

A

-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

63
Q

What is Express-validator? How do you use it?

A

-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
});

64
Q

What is Connect-flash? How do you use it?

A

-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());