Express.
js Fundamentals
1. What is [Link]? [Link] (or simply Express) is a minimalist and flexible
[Link] web application framework. It provides a robust set of features to build
web and mobile applications, especially APIs. Framework 뼈대 (Korean for
framework/skeleton)
2. Who created [Link]? TJ Holowaychuk.
3. Why use [Link]? It simplifies the process of building web servers and
APIs with [Link]. It provides helpful tools for routing, middleware, handling
requests, and sending responses.
4. Is [Link] a front-end or back-end framework? It's a back-end framework.
It runs on the server using [Link].
5. What are some key features of [Link]?
o Routing: Defines how your application responds to different URLs and
HTTP methods.
o Middleware: Functions that can process requests and responses.
o Templating Engine Support: Allows dynamic HTML generation.
o Fast and Lightweight: Minimal core, allowing flexibility.
6. What is [Link] and how does it relate to [Link]? [Link] is the runtime
environment that allows you to run JavaScript on the server. [Link] is a
framework built on top of [Link] to make web development easier.
7. What is a web framework? A web framework provides a standard way to build
and deploy web applications. It often includes libraries, tools, and conventions
to speed up development.
8. How do you install [Link]? Using npm (Node Package Manager): npm
install express --save
9. How do you create a simple [Link] application?
JavaScript
const express = require('express');
const app = express();
const port = 3000;
[Link]('/', (req, res) => {
[Link]('Hello World!');
});
[Link](port, () => {
[Link](`Example app listening at [Link]
});
10. What is app in const app = express();? It's an instance of the Express
application. This object has methods for routing, middleware, and other
application settings.
11. What does [Link]() do? It starts an HTTP server and listens for incoming
connections on a specified host and port.
Routing
12. What is routing in [Link]? Routing refers to how an application’s
endpoints (URIs) respond to client requests. It determines what code is
executed for a specific URL and HTTP method.
13. How do you define a route in Express? Using methods on the app object
corresponding to HTTP methods (e.g., [Link](), [Link](), [Link](),
[Link]()). Example: [Link]('/users', (req, res) => { /* ... */ });
14. What are req and res objects in route handlers?
o req (Request): An object representing the incoming HTTP request (e.g.,
URL, headers, query parameters, body).
o res (Response): An object representing the outgoing HTTP response that
the server will send back (e.g., sending data, setting status codes).
15. How do you handle a GET request? Using [Link]('/path', (req, res) => { /*
handler logic */ });
16. How do you handle a POST request? Using [Link]('/path', (req, res) => { /*
handler logic */ });
17. What are route parameters? How do you access them? Segments of the URL
used to capture values. They are prefixed with a colon (:). Example:
/users/:userId Access them via [Link]: const userId = [Link];
18. What are query parameters? How do you access them? Key-value pairs
appended to the URL after a ?. Example: /search?term=express&page=1 Access
them via [Link]: const searchTerm = [Link];
19. What is [Link]()? A special routing method that matches all HTTP methods for
a specified path. Useful for applying middleware to a specific path for all request
types.
20. How can you chain route handlers for the same path? Using
[Link]('/path').get(handler1).post(handler2);
21. What is [Link]()? A mini Express application that can be used to
group route handlers. It helps in organizing your routes into modular pieces.
22. Why use [Link]()? To create modular and mountable route handlers.
Makes your application more organized and easier to manage as it grows.
Middleware
23. What is middleware in [Link]? Middleware functions are functions that
have access to the request object (req), the response object (res), and the
next function in the application’s request-response cycle. They can execute
code, make changes, end the cycle, or pass control to the next middleware.
24. What can middleware functions do?
o Execute any code.
o Make changes to the request and response objects.
o End the request-response cycle.
o Call the next middleware function in the stack.
25. What is the next() function in middleware? A function that, when called,
passes control to the next middleware function in the stack. If it's not called,
the request will be left hanging.
26. How do you use middleware in Express? Using [Link]() or by providing it
directly to a route handler method (like [Link]()). Example:
[Link](myMiddlewareFunction);
27. What are the different types of middleware?
o Application-level middleware: Bound to [Link]() or [Link]().
o Router-level middleware: Bound to an instance of [Link]().
o Error-handling middleware: Special middleware with four arguments
(err, req, res, next).
o Built-in middleware: Provided by Express (e.g., [Link](),
[Link]()).
o Third-party middleware: Installed via npm (e.g., body-parser, morgan,
cors).
28. What is [Link]()? A built-in middleware function to parse incoming
requests with JSON payloads. It makes [Link] available with the parsed
JSON data.
29. What is [Link]()? A built-in middleware function to parse
incoming requests with URL-encoded payloads (like form submissions). It
makes [Link] available.
30. What is [Link]()? A built-in middleware function to serve static files
such as images, CSS files, and JavaScript files. Example:
[Link]([Link]('public')); will serve files from the public directory.
31. What is body-parser middleware? Why was it used? body-parser was a
popular third-party middleware used to parse incoming request bodies (JSON,
URL-encoded). In modern Express (4.16.0+), its functionality (json() and
urlencoded()) is now built into Express itself.
32. What is morgan middleware? A popular third-party HTTP request logger
middleware. It logs details about incoming requests to the console, which is
useful for debugging.
33. What is cors middleware? A third-party middleware to enable Cross-Origin
Resource Sharing (CORS). It adds necessary HTTP headers to allow requests
from different origins (domains).
34. How do you create custom middleware? Write a function that takes req, res,
and next as arguments.
JavaScript
function myCustomMiddleware(req, res, next) {
[Link]('Time:', [Link]());
next(); // Call next() to pass control
}
[Link](myCustomMiddleware);
35. In what order does middleware execute? Middleware functions are executed
in the order they are defined and added to the stack using [Link]() or route
methods.
36. Can middleware modify req and res objects? Yes, that's one of its main
purposes (e.g., adding properties to req or setting headers on res).
Error Handling
37. How do you handle errors in [Link]? By defining error-handling
middleware functions. These functions have four arguments: (err, req, res,
next).
38. How do you define an error-handling middleware? It must be defined with four
arguments. It's typically placed at the end of the middleware stack.
JavaScript
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send('Something broke!');
});
39. How do you pass an error to the error-handling middleware? By calling
next(err) with an error object from any regular middleware or route handler.
40. What happens if you don't call next() in a regular middleware? The request
will hang, and the client will not receive a response, eventually timing out.
41. What happens if you don't call next(err) in an error-handling middleware? If
it's the last error handler, the request might hang or a default HTML error page
might be sent by Express. If you intend to handle the error and send a response,
you don't need to call next(err). If you want to pass it to another error handler, you
can.
42. How do you handle 404 (Not Found) errors? Define a middleware function at
the very end of your middleware and route stack (before error handlers) that
sends a 404 response.
JavaScript
[Link]((req, res, next) => {
[Link](404).send("Sorry, can't find that!");
});
Request & Response Objects
43. What is [Link]? An object containing route parameters (named parts of
the URL path). Example: for /users/:id, [Link].
44. What is [Link]? An object containing URL query string parameters (after
the ?). Example: for /search?name=book, [Link].
45. What is [Link]? An object containing the parsed request body data,
typically from POST or PUT requests (e.g., form data, JSON). Requires
middleware like [Link]() or [Link]() to be populated.
46. What is [Link]? A string indicating the HTTP request method (e.g., 'GET',
'POST').
47. What is [Link]? A string containing the path part of the request URL.
48. What is [Link]? An object containing the HTTP request headers.
49. What is [Link]()? A method to send an HTTP response. It can send strings,
objects (which are stringified as JSON), arrays, or Buffers. It also sets the
Content-Type header appropriately.
50. What is [Link]()? A method to send a JSON response. It converts a JavaScript
object or array to a JSON string and sets the Content-Type header to
application/json.
51. What is [Link]()? A method to set the HTTP status code for the response.
It's chainable. Example: [Link](200).send('OK');
52. What is [Link]()? Sets the response HTTP status code and sends its
string representation as the response body. Example: [Link](404);
sends "Not Found".
53. What is [Link]()? A method to render a view template (like Pug, EJS,
Handlebars) and send the resulting HTML string to the client. Requires a
template engine to be configured.
54. What is [Link]()? A method to redirect the client to a different URL.
Example: [Link]('/login');
55. What is [Link]() or [Link]()? Methods to set HTTP response headers.
Example: [Link]('Cache-Control', 'no-cache');
56. What is [Link]()? A low-level method to quickly end the response process
without any data. Often used when data has already been written to the
response stream.
Templating Engines
57. What is a template engine? Software that allows you to use static template
files in your application. At runtime, the template engine replaces variables in a
template file with actual values and transforms the template into an HTML file
sent to the client.
58. How do you use a template engine with Express?
1. Install the engine (e.g., npm install ejs).
2. Set the view engine and views directory in your app:
JavaScript
[Link]('view engine', 'ejs');
[Link]('views', './views'); // Default directory
3. Use [Link]('templateName', { data }) in your route handlers.
59. What are some popular template engines used with Express?
o Pug (formerly Jade)
o EJS (Embedded JavaScript)
o Handlebars
60. What does [Link]('view engine', 'ejs') do? It tells Express to use EJS as the
default template engine when [Link]() is called without a file extension.
Working with Databases
61. How do you connect to a database (e.g., MongoDB, PostgreSQL) from an
Express app? You typically use a database driver or an ORM/ODM library
specific to that database.
o For MongoDB: Mongoose (ODM) or the native MongoDB driver.
o For PostgreSQL: pg (driver) or Sequelize/TypeORM (ORM). You establish
the connection once when your application starts.
62. What is an ORM/ODM?
o ORM (Object-Relational Mapper): A technique that lets you query and
manipulate data from a relational database using an object-oriented
paradigm (e.g., Sequelize for SQL databases).
o ODM (Object-Document Mapper): Similar to ORM, but for document
databases like MongoDB (e.g., Mongoose).
File Uploads
63. How do you handle file uploads in Express? Using middleware specifically
designed for handling multipart/form-data, which is the encoding used for file
uploads. A popular choice is multer.
64. What is multer? A [Link] middleware for handling multipart/form-data,
primarily used for uploading files.
65. How does multer work (briefly)? It adds a body object and a file or files object
to the request object. The file or files object contains information about the
uploaded file(s).
Security
66. What are some common security best practices for Express apps?
o Use HTTPS.
o Validate and sanitize user input to prevent XSS, SQL injection, etc.
o Use Helmet middleware to set various security-related HTTP headers.
o Implement proper authentication and authorization.
o Protect against CSRF attacks.
o Keep dependencies updated.
o Use rate limiting.
67. What is Helmet middleware? A collection of 12+ smaller middleware
functions that set various HTTP headers to help secure your Express
application (e.g., X-Content-Type-Options, Strict-Transport-Security, X-Frame-
Options).
68. What is CSRF (Cross-Site Request Forgery)? An attack that tricks a victim into
submitting a malicious request to a web application they are already
authenticated with.
69. How can you protect against CSRF in Express? Using middleware like csurf
that implements CSRF token protection.
70. What is XSS (Cross-Site Scripting)? An attack where malicious scripts are
injected into otherwise benign and trusted websites.
71. How to prevent XSS in Express?
o Validate and sanitize all user input.
o Encode output correctly when displaying user-generated content.
o Use Content-Security-Policy headers (often set by Helmet).
Environment Variables
72. Why use environment variables in an Express app? To store configuration
settings that vary between environments (development, testing, production)
without hardcoding them, such as API keys, database credentials, and port
numbers.
73. How do you use environment variables in Express? Access them via
[Link].VARIABLE_NAME. It's common to use a .env file and the dotenv
package to load these variables during development.
74. What is the dotenv package? A zero-dependency module that loads
environment variables from a .env file into [Link].
Structuring an Express Application
75. How can you structure a larger Express application?
o Modularize routes: Use [Link]() for different parts of your API
(e.g., [Link], [Link]).
o Separate concerns: Create folders for controllers, models, services,
middleware, config, etc.
o Use a common structure like MVC (Model-View-Controller) or a variation.
76. What is the MVC pattern? A design pattern that separates an application into
three interconnected components:
o Model: Manages the data, logic, and rules of the application.
o View: The user interface (what the user sees, often a template).
o Controller: Accepts input and converts it into commands for the model
or view.
Testing
77. Why is testing Express applications important? To ensure routes,
middleware, and controllers work as expected, catch bugs early, and allow for
confident refactoring.
78. What are some popular testing frameworks for [Link]/Express?
o Jest
o Mocha (often with Chai for assertions and Sinon for spies/stubs)
o Supertest (for testing HTTP endpoints)
79. What is Supertest? An HTTP assertion library that allows you to test your
Express API endpoints by making actual HTTP requests to your application and
verifying the responses.
Miscellaneous & Advanced
80. What is [Link]? An object whose properties are local variables available
within the application's templates during a single request-response cycle.
81. What is [Link]? An object whose properties are local variables scoped to
the current request, and therefore available only to the view(s) rendered during
that request/response cycle.
82. What is the difference between [Link] and [Link]?
o [Link]: Variables available throughout the entire application, across
all requests (e.g., app name, helper functions).
o [Link]: Variables specific to a single request-response cycle (e.g.,
user-specific data for a view).
83. How can you get the client's IP address? [Link] or
[Link]. Be aware of proxies; [Link]['x-forwarded-
for'] might be needed.
84. What is scaffolding in Express? Generating a basic project structure and
boilerplate code for an Express application. Tools like express-generator can do
this.
85. What is express-generator? A command-line tool to quickly create a
skeleton Express application.
86. What is the purpose of next('route')? When called in a router's middleware or
route handler, it skips the rest of the handlers in the current router and
passes control to the next route that matches the path.
87. Can you use Promises with Express route handlers? Yes. If a route handler
returns a Promise, Express (v5+) or error handling middleware can catch
rejections. For older versions, you'd typically use .catch(next) to pass errors.
88. How does Express handle asynchronous errors in route handlers by default
(older versions)? In older versions (pre-Express 5), if an asynchronous error
occurs (e.g., in a Promise without .catch(next) or a callback), it might not be
caught by Express's default error handler, potentially crashing the process.
You needed to explicitly call next(err).
89. How has error handling for async routes improved in Express 5? Express 5
automatically catches errors from route handlers that return Promises and
passes them to the error handling middleware, eliminating the need for explicit
.catch(next).
90. What is [Link](headerName)? A method to get the value of a specific HTTP
request header. It's case-insensitive.
91. What is [Link]()? A method to set cookies in the HTTP response.
92. What is [Link]? An object containing cookies sent by the client. Requires
cookie-parser middleware.
93. What is cookie-parser middleware? Middleware to parse Cookie header and
populate [Link] with an object keyed by cookie names.
94. What is session management in Express? The process of maintaining user
state across multiple requests. Usually involves storing session data on the
server and using a session ID cookie on the client. Libraries like express-session
are used.
95. What is express-session? Middleware for managing sessions in Express
applications.
96. How can you serve different content based on the Accept request header?
Using [Link]() or by manually checking [Link]() or [Link]('Accept') and
sending the appropriate response.
97. What is RESTful API design? Designing APIs according to REST principles,
focusing on resources, using standard HTTP methods for actions, and being
stateless. Express is well-suited for building RESTful APIs.
98. How would you structure the URL for updating a specific user with ID 123 in a
RESTful API? Typically PUT /users/123 or PATCH /users/123.
99. What HTTP status code would you send for a successful resource creation
(e.g., after a POST request)? 201 Created.
100. What HTTP status code would you send if a client tries to access a
resource they don't have permission for (but they are authenticated)? 403
Forbidden.