Express.js REST API
- 31Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the primary purpose of npm init -y when setting up a Node.js application?
31 questions
- 1
What is the primary purpose of
npm init -ywhen setting up a Node.js application?Model answer
npm init -yinitializes a Node.js project by creating apackage.jsonfile with default values, which is essential for managing project metadata and dependencies.Explanation
This command is the first step in setting up a new Node.js project. The
-yflag tells npm to use default values for all prompts, quickly generating thepackage.jsonfile without requiring user input. This file tracks project dependencies, scripts, and other metadata, making it crucial for any Node.js application. - 2
Which command is used to install the Express.js framework into a Node.js project?
Model answer
The command
npm install expressis used to install the Express.js framework.Explanation
Express.js is the only direct dependency needed for building a basic REST API as demonstrated.
npm installfollowed by the package name fetches the package from the npm registry and adds it to the project'snode_modulesdirectory and updates thepackage.jsonfile. - 3
What is the typical file name convention for the main Express.js application file?
Model answer
The main Express.js application file is commonly named
index.jsormain.js.Explanation
While the name can be arbitrary,
index.jsis a widely adopted convention for the primary entry point of many JavaScript applications, including those built with Express. This makes it easier for other developers to understand the project structure. - 4
Explain the role of
app.listen(port, callback)in an Express.js application.Model answer
app.listen()starts the Express server and makes it listen for incoming requests on a specified port, executing a callback function once the server is ready.Explanation
This function is crucial for making the Express application accessible over a network. The
portparameter (e.g., 3000) specifies which port the server should bind to, and thecallbackfunction is executed once the server successfully starts listening, often used for logging a message to the console. - 5
What happens if you navigate to
localhost:3000after starting an Express server withapp.listen(3000)but without defining any routes?Model answer
You will receive an error message in the browser, typically indicating that no route exists for the requested path.
Explanation
Express servers handle requests by matching them against defined routes. If no routes are defined, or if the root path
/does not have a handler, the server cannot fulfill the request and will respond with a 'Cannot GET /' or similar error, as it doesn't know how to process the incoming request. - 6
How do you define a GET route for fetching all to-do items in Express.js?
Model answer
A GET route for fetching all to-do items is defined using
app.get('/todos', (req, res) => { ... });.Explanation
The
app.get()method is used to handle HTTP GET requests. The first argument is the path (/todos), and the second is a callback function that receives therequest(req) andresponse(res) objects. This route would be responsible for retrieving a collection of resources, such as all to-do items from a data source. - 7
What do the
reqandresparameters represent in an Express route handler callback?Model answer
reqrepresents the incoming HTTP request object, containing data from the client, whileresrepresents the HTTP response object, used to send data back to the client.Explanation
The
req(request) object holds information about the incoming request, such as parameters, body, headers, and query strings. Theres(response) object is used to build and send the HTTP response back to the client, including setting status codes, headers, and sending data (e.g., JSON, HTML). - 8
When should you use
res.json()instead ofres.send()in an Express route handler?Model answer
res.json()should be used when sending JSON data as a response, as it automatically sets theContent-Typeheader toapplication/jsonand stringifies the object, whereasres.send()can send various types of responses.Explanation
While
res.send()is a more general-purpose method that can send strings, buffers, objects, or arrays,res.json()is specifically tailored for JSON responses. It ensures proper JSON formatting and sets the correct MIME type, which is crucial for REST APIs that primarily communicate using JSON. - 9
Why is it recommended to install
nodemonglobally (npm install nodemon -g) for development?Model answer
nodemonis recommended for global installation in development to enable hot reloading of the Node.js application, automatically restarting the server when file changes are detected.Explanation
During development, continuously stopping and restarting the server manually after every code change is inefficient.
nodemonmonitors for changes in your source files and automatically restarts the Node.js process, significantly speeding up the development workflow. Global installation makes it accessible from any project. - 10
How do you configure
nodemonto run your Express application using annpm run devscript?Model answer
In the
package.jsonfile, add a"dev": "nodemon index.js"entry under thescriptsobject, then runnpm run dev.Explanation
This setup allows you to execute
nodemon index.jsusing a simplernpm run devcommand. Thescriptssection inpackage.jsondefines custom commands, making it convenient to manage and run project-specific tasks like starting the development server withnodemon. - 11
What tool can be used to test various HTTP requests (GET, POST, PUT, DELETE) to an API without using the browser?
Model answer
Tools like Postman or Insomnia can be used to test various HTTP requests to an API.
Explanation
Browsers are typically limited to making GET requests. For testing other HTTP methods (POST, PUT, DELETE, etc.), or for sending custom headers and body data, dedicated API testing tools like Postman or Insomnia provide a user-friendly interface to construct and send requests, inspect responses, and manage collections of API calls.
- 12
What HTTP verb is typically used for adding new data to a resource collection?
Model answer
The HTTP verb
POSTis typically used for adding new data to a resource collection.Explanation
POST requests are designed to submit data to a specified resource, which often results in the creation of a new resource on the server. For example, creating a new to-do item would typically involve a POST request to the
/todosendpoint with the new to-do's data in the request body. - 13
Why is
app.use(express.json())necessary for handling POST requests with JSON bodies in Express.js?Model answer
app.use(express.json())is necessary to parse incoming request bodies with JSON payloads, making the JSON data available onreq.body.Explanation
By default, Express does not parse the body of incoming requests.
express.json()is a built-in middleware function that parses JSON data from the request body. Without it,req.bodywould beundefined, and the server would not be able to access the data sent by the client in a POST or PUT request. - 14
How do you extract the
titleproperty from a JSON request body in an Express route handler?Model answer
You can extract the
titleproperty usingreq.body.titleor by destructuring it asconst { title } = req.body;.Explanation
After the
express.json()middleware has parsed the request body, the parsed JSON object is attached toreq.body. You can then access individual properties of this object using dot notation (req.body.title) or JavaScript's object destructuring syntax for a more concise way (const { title } = req.body;). - 15
What is the purpose of the
uuidpackage and itsv4method in the context of creating new to-do items?Model answer
The
uuidpackage'sv4method generates universally unique identifiers (UUIDs) which are random, unique strings used as IDs for new to-do items, ensuring each item has a distinct identifier.Explanation
When creating new records, it's essential to assign them a unique ID.
uuid(specificallyv4which generates random UUIDs) provides a robust way to create these unique string identifiers. This prevents ID collisions, especially in a distributed environment, and simplifies operations like fetching or updating specific items. - 16
In a REST API, why is returning the newly added record in a POST request response considered good practice?
Model answer
Returning the newly added record in a POST request response is good practice because it provides the client with the final state of the resource, including any server-generated properties like its unique ID.
Explanation
When a client sends data to create a new resource, the server often adds properties like an ID, creation timestamp, or default values. Returning the complete, server-generated record allows the client to immediately update its local state with the authoritative version of the resource, making subsequent operations (like getting or updating that specific item) easier.
- 17
How do you define a GET route to fetch a single to-do item by its ID using URL parameters in Express.js?
Model answer
A GET route to fetch a single to-do item by its ID is defined as
app.get('/todos/:id', (req, res) => { ... });.Explanation
The
/:idsegment in the path signifies a URL parameter. The colon (:) denotes thatidis a placeholder for a dynamic value. When a request matches this route (e.g.,/todos/123), the value '123' will be available inreq.params.id. - 18
How do you access the
idfrom the URL parameter in an Express route handler defined as'/todos/:id'?Model answer
You access the
idfrom the URL parameter usingreq.params.idor by destructuring it asconst { id } = req.params;.Explanation
The
req.paramsobject contains properties mapped to the named URL parameters defined in the route path. For a route like/todos/:id, a request to/todos/abcwould result inreq.params.idbeing 'abc'. - 19
Why is storing to-do items in a simple JavaScript array not suitable for data persistence across server restarts?
Model answer
Storing to-do items in a simple JavaScript array is not suitable for data persistence because the array's contents are lost every time the server restarts, as variables in memory are reset.
Explanation
In-memory data structures like arrays are volatile. When the Node.js process terminates (e.g., due to a code change, crash, or manual restart), all data held in application variables is cleared. To achieve persistence, data must be stored in a non-volatile medium like a database (e.g., MongoDB, PostgreSQL) or a file system.
- 20
What HTTP verb is typically used for updating an existing resource, and why?
Model answer
The HTTP verb
PUTis typically used for updating an existing resource because it represents a complete replacement of the resource at the specified URL.Explanation
A PUT request is idempotent, meaning that making the same request multiple times will have the same effect as making it once. It's used to update an entire resource; the client sends a complete representation of the resource to be stored at the specified URI. While
PATCHis for partial updates,PUTis for full replacements. - 21
How can you find the index of a specific to-do item in an array based on its ID?
Model answer
You can find the index of a specific to-do item using the
findIndex()array method, liketodos.findIndex(todo => todo.id === id);.Explanation
The
findIndex()method iterates over an array and returns the index of the first element for which the provided testing function returnstrue. If no elements satisfy the condition, it returns -1. This is useful when you need to directly modify an item in an array by its index. - 22
What is the typical HTTP verb used for deleting a resource?
Model answer
The HTTP verb
DELETEis typically used for deleting a resource.Explanation
A DELETE request is used to remove the specified resource. Similar to PUT, DELETE requests are also idempotent.
- 23
How can you remove a specific to-do item from an array based on its ID without mutating the original array?
Model answer
You can remove a specific to-do item using the
filter()array method, liketodos = todos.filter(todo => todo.id !== id);, which creates a new array.Explanation
The
filter()method creates a new array with all elements that pass the test implemented by the provided function. By filtering out the to-do item whoseidmatches the one to be deleted, you effectively create a new array that excludes that item, without directly modifying the original array (though in the example, thetodosvariable is reassigned to the new filtered array). - 24
What is the primary benefit of organizing routes into separate files (e.g.,
routes/todos.js) using Express'sRouter?Model answer
Organizing routes into separate files using
Routerimproves code organization, modularity, and maintainability, especially for larger applications with many different resource types.Explanation
As applications grow, having all route definitions in a single
index.jsfile can become unmanageable.express.Router()allows you to create modular, mountable route handlers. Each file can manage routes for a specific resource (e.g., 'todos', 'animals'), making the codebase cleaner, easier to navigate, and more scalable. - 25
How do you create a modular router in Express.js for a specific set of routes?
Model answer
You create a modular router by importing Express and then invoking
express.Router(), likeconst router = require('express').Router();.Explanation
express.Router()creates a new router object. This object behaves like a mini-application, capable of defining its own middleware and routes. These routers can then be mounted on specific paths in the main application usingapp.use(), allowing for hierarchical route definitions. - 26
What is
module.exports = router;used for in atodos.jsroute file?Model answer
module.exports = router;is used to export the defined router object fromtodos.js, making it available for import and use in other files, such asindex.js.Explanation
In Node.js's CommonJS module system,
module.exportsspecifies what a module exposes to other modules when it'srequire()d. By exporting therouterinstance, the main application file can then import and mount these modular routes. - 27
How do you integrate a modular router (e.g.,
todosRouterfromroutes/todos.js) into the main Express application (index.js)?Model answer
You integrate a modular router using
app.use('/todos', require('./routes/todos'));, where'/todos'is the base path for all routes defined intodos.js.Explanation
The
app.use()method, when given a path as its first argument and a router as its second, mounts the router at that specific base path. This means any route defined within thetodosRouter(e.g.,/) will now be accessible at/todos/. This avoids repeating the/todosprefix in every route within thetodos.jsfile. - 28
Define 'middleware' in the context of Express.js and explain its typical execution flow.
Model answer
Middleware in Express.js is a function that has access to the request and response objects, and the next middleware function in the application's request-response cycle. It executes before the request reaches the final route handler.
Explanation
Middleware functions can perform various tasks: executing code, making changes to the request and response objects, ending the request-response cycle, or calling the next middleware function in the stack. They are executed in the order they are defined. A common use case is authentication, where middleware checks credentials before allowing the request to proceed to the intended route.
- 29
What is the purpose of the
next()function in an Express.js middleware?Model answer
The
next()function in Express.js middleware is used to pass control to the next middleware function or route handler in the application's request-response cycle.Explanation
If a middleware function does not end the request-response cycle (e.g., by sending a response), it must call
next()to pass control to the next function. Ifnext()is not called, the request will be left hanging, and subsequent middleware or the route handler will not be executed. - 30
How can you implement a simple authentication check using middleware that examines a request header?
Model answer
You can implement a simple authentication middleware by checking a specific request header using
req.header('Authenticated'). If the header value is 'yes', callnext(); otherwise, send a403 Forbiddenresponse.Explanation
This example demonstrates how middleware can inspect incoming request properties (like headers) to make decisions. If the 'Authenticated' header is present and its value is 'yes', the request is allowed to proceed to the next middleware or route handler via
next(). If not, a403 Forbiddenstatus is returned, preventing unauthorized access to subsequent resources. - 31
How do you apply a custom authentication middleware (
checkAuth) to specific routes?Model answer
You apply
checkAuthmiddleware by including it as an argument between the route path and the route handler callback, likerouter.get('/', checkAuth, (req, res) => { ... });.Explanation
Middleware functions can be added as arguments to route definitions. When a request matches this route, the
checkAuthmiddleware will execute first. IfcheckAuthcallsnext(), then the final route handler callback will execute. This allows for granular control over which routes require specific processing, such as authentication.

Ask anything
We've read this whole study set, so questions about it get the best answers.