Express.js REST API
- 34Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the primary purpose of npm init -y when setting up an Express.js application?
What is the primary purpose of npm init -y when setting up an Express.js application?
34 questions
- 1
What is the primary purpose of
npm init -ywhen setting up an Express.js application?- A
It initializes a Node.js project and generates the
package.jsonfile. - B
It creates a new directory for the Express.js application files.
- C
It automatically sets up hot reloading for the Node.js application.
- D
It installs the Express.js framework globally on your system.
Correct answer
AIt initializes a Node.js project and generates the
package.jsonfile.Explanation
The command
npm init -yis used to initialize a new Node.js project. The-yflag automatically answers 'yes' to all prompts, quickly generating apackage.jsonfile, which is essential for managing project dependencies and scripts. - A
- 2
Which command is used to install Express.js as a dependency for a Node.js project?
- A
npm install express --global
- B
npm init express --package
- C
npm start express --save-dev
- D
npm install express --save-prod
Correct answer
Dnpm install express --save-prod
Explanation
To install Express.js as a project dependency, the command
npm install expressis used. The--save-prodis often implied or can be explicitly added, makingexpressa production dependency recorded inpackage.json. - A
- 3
What is the conventional file name for the main server application in an Express.js project?
- A
The file is commonly referred to as
index.jsormain.js. - B
The file should always be named
app.jsfor clarity. - C
The file must be named
server.jsto function correctly. - D
The file is typically named
main.jsfor most applications.
Correct answer
AThe file is commonly referred to as
index.jsormain.js.Explanation
While you can name the main server file whatever you prefer, the common conventions are
index.jsormain.js. The content explicitly mentionsindex.jsas the chosen convention for the example. - A
- 4
How do you instantiate an Express.js application object after requiring the Express module?
- A
const app = new ExpressApplication();
- B
const app = Express();
- C
const app = express.createApp();
- D
const app = express();
Correct answer
Dconst app = express();
Explanation
After importing the Express module using
const express = require('express');, you instantiate an Express application by invokingexpress()as a function:const app = express();. - A
- 5
Which method is used to start the Express.js server and make it listen for incoming requests?
- A
app.start(port, callback);
- B
app.listen(port, callback);
- C
app.run(port, callback);
- D
app.connect(port, callback);
Correct answer
Bapp.listen(port, callback);
Explanation
The
app.listen()method is used to bind the server to a specific port and listen for connections. It takes the port number as the first argument and an optional callback function to execute once the server starts. - A
- 6
What command is used to execute a Node.js application file (e.g.,
index.js) from the terminal?- A
execute index.js
- B
node index.js
- C
node run index.js
- D
start index.js
Correct answer
Bnode index.js
Explanation
To run a Node.js application, you use the
nodecommand followed by the name of the main JavaScript file, for example,node index.js. This executes the script in the Node.js runtime. - A
- 7
Why would
localhost:3000show 'Cannot GET /' after setting up an Express server initially?- A
The application has not yet defined any specific routes to handle requests.
- B
The server is not configured to listen on port 3000 correctly.
- C
The
package.jsonfile is missing a 'start' script for the server. - D
There is a firewall blocking incoming connections to port 3000.
Correct answer
AThe application has not yet defined any specific routes to handle requests.
Explanation
When an Express server is running but displays 'Cannot GET /' for the root URL, it indicates that no route handler has been defined for the root path ('/') and the HTTP GET method. The server is up, but it doesn't know how to respond to that specific request.
- A
- 8
Which HTTP verb is considered best practice for retrieving data in a REST API?
- A
The
GETverb is the standard for requesting data from a server. - B
The
PUTverb should be used when simply fetching data. - C
The
POSTverb is most appropriate for fetching information. - D
The
PATCHverb is typically used for data retrieval operations.
Correct answer
AThe
GETverb is the standard for requesting data from a server.Explanation
In RESTful API design, the
GETHTTP verb is specifically intended for retrieving resources or data from the server. It should not have side effects and is idempotent and safe. - A
- 9
What are the two standard parameters passed to the callback function of an Express route handler?
- A
req (request) and res (response)
- B
err (error) and data (response data)
- C
path (route path) and handler (callback function)
- D
req (request) and next (next middleware function)
Correct answer
Areq (request) and res (response)
Explanation
The callback function for an Express route handler always receives two primary parameters:
req(the request object, containing incoming request details) andres(the response object, used to send data back to the client). - A
- 10
How can an Express route handler send back JSON data as a response to the client?
- A
res.write(JSON.stringify(data));
- B
res.sendJson(data);
- C
res.json(data);
- D
res.return(data, 'json');
Correct answer
Cres.json(data);
Explanation
The
res.json()method in Express is specifically designed to send a JSON response to the client. It automatically sets theContent-Typeheader toapplication/jsonand converts the JavaScript object or array to a JSON string. - A
- 11
What is
nodemonprimarily used for in Node.js development?- A
It automatically restarts the Node.js application on file changes.
- B
It manages Node.js package dependencies during installation.
- C
It provides a debugger for stepping through Node.js code.
- D
It encrypts sensitive data transmitted over the network.
Correct answer
AIt automatically restarts the Node.js application on file changes.
Explanation
nodemonis a utility that monitors for any changes in your source code and automatically restarts your Node.js server. This is crucial for development as it provides a 'hot reload' experience, saving developers from manually restarting the server after every change. - A
- 12
How do you install
nodemonglobally on your system using npm?- A
npm install nodemon --save-dev
- B
npm install nodemon -g
- C
npm add nodemon -g
- D
npm init nodemon -y
Correct answer
Bnpm install nodemon -g
Explanation
To install
nodemonglobally, making it available from any directory, you usenpm install nodemon -g. The-gflag indicates a global installation. For Mac/Linux,sudomight be needed beforenpm. - A
- 13
Where should a
devscript for runningnodemonbe added in a Node.js project?- A
Directly in the
index.jsfile at the top. - B
Inside the
dependenciessection ofpackage.json. - C
In a separate
nodemon.jsonconfiguration file. - D
Within the
scriptssection of thepackage.jsonfile.
Correct answer
DWithin the
scriptssection of thepackage.jsonfile.Explanation
Custom scripts, such as a
devscript fornodemon, are defined within thescriptssection of thepackage.jsonfile. This allows you to run commands likenpm run devto executenodemon index.js. - A
- 14
Which tool can be used to test various HTTP requests (GET, POST, PUT, DELETE) to an API?
- A
The
npmcommand-line interface - B
A standard web browser's address bar
- C
Postman or Insomnia
- D
Node.js built-in HTTP module
Correct answer
CPostman or Insomnia
Explanation
Tools like Postman and Insomnia are API clients that allow developers to construct and send various HTTP requests (GET, POST, PUT, PATCH, DELETE, etc.), inspect responses, and manage request headers and bodies, making them invaluable for API testing.
- A
- 15
What is the appropriate HTTP verb for adding new data to a resource on the server?
- A
The
POSTverb is designated for creating or adding new data. - B
The
GETverb is ideal for submitting new data records. - C
The
DELETEverb can also be used for data insertion. - D
The
PUTverb is primarily used for creating new resources.
Correct answer
AThe
POSTverb is designated for creating or adding new data.Explanation
The
POSTHTTP verb is the standard and best practice for sending data to the server to create a new resource. It is typically used for submitting forms or uploading files. - A
- 16
Where is data typically passed when making a
POSTrequest to create a new resource in a REST API?- A
The data is passed as part of the dynamic route parameters.
- B
The data is usually included within the HTTP request headers.
- C
The data is always appended as query parameters in the URL path.
- D
The data is commonly sent within the body of the request.
Correct answer
DThe data is commonly sent within the body of the request.
Explanation
When creating a new resource via a
POSTrequest, the data representing the new resource is typically sent in the body of the HTTP request. This allows for sending complex data structures, often in JSON format. - A
- 17
What is the purpose of
app.use(express.json())in an Express.js application?- A
It automatically compresses JSON responses for faster transmission.
- B
It parses incoming request bodies with JSON payloads.
- C
It validates the JSON structure of outgoing responses.
- D
It enables the application to serve static JSON files from the server.
Correct answer
BIt parses incoming request bodies with JSON payloads.
Explanation
app.use(express.json())is a built-in middleware function in Express. It parses incoming requests with JSON payloads, making the parsed data available underreq.body. Without this middleware,req.bodywould be undefined when JSON data is sent. - A
- 18
How do you access the
titleproperty from a JSON request body in an Express route handler?- A
const title = req.query.title;
- B
const title = req.headers.title;
- C
const title = req.body.title;
- D
const title = req.params.title;
Correct answer
Cconst title = req.body.title;
Explanation
After using
express.json()middleware, data sent in the request body (like a JSON object with atitleproperty) becomes accessible throughreq.body.title. Destructuringconst { title } = req.body;is also a common practice. - A
- 19
What external package is recommended for generating unique string identifiers for records?
- A
The
uuidpackage for creating unique IDs. - B
The
cryptomodule built into Node.js. - C
The
id-generatornpm library for sequential numbers. - D
A simple timestamp concatenated with a random number.
Correct answer
AThe
uuidpackage for creating unique IDs.Explanation
The
uuidpackage is a popular choice for generating universally unique identifiers (UUIDs), which are often used as unique string IDs for database records or resources in a REST API, as demonstrated withv4UUIDs. - A
- 20
What is the typical response sent back after successfully adding a new record via a
POSTrequest?- A
A success message with status code 200.
- B
An empty response with no body.
- C
The newly added record itself.
- D
The entire updated list of records.
Correct answer
CThe newly added record itself.
Explanation
While there are different approaches, the content suggests that for most
POSTrequests that add data, it is common practice to respond with the record that was newly added. This allows the client to confirm the creation and receive the full data, including any server-generated fields like an ID. - A
- 21
How is a dynamic ID parameter (e.g.,
:id) accessed from the URL in an Express route handler?- A
By parsing the ID directly from
req.url. - B
By extracting the ID from
req.params.id. - C
By using
req.body.idto retrieve the ID. - D
By accessing
req.query.idfor the ID.
Correct answer
BBy extracting the ID from
req.params.id.Explanation
When a route path includes a dynamic segment like
/todos/:id, the value of:idis captured and made available in thereq.paramsobject asreq.params.id. This is how you access specific resource identifiers from the URL path. - A
- 22
Why does the
todosarray become empty after every server restart in the given example?- A
The
todosarray is a global variable and gets reset bynodemon. - B
The
package.jsonconfiguration forces a reset of application state. - C
The data is not persisted to a database and resides only in memory.
- D
The application explicitly clears the array upon server startup.
Correct answer
CThe data is not persisted to a database and resides only in memory.
Explanation
In the provided example, the
todosarray is a simple in-memory variable. When the server restarts (e.g., due tonodemondetecting changes), the Node.js process is re-initialized, and all in-memory variables, including thetodosarray, are reset to their initial state. Data persistence requires a database. - A
- 23
Which HTTP verb is typically used for updating an existing resource entirely or toggling a status?
- A
The
PUTverb is generally used for replacing or updating resources. - B
The
POSTverb is suitable for modifying existing data entries. - C
The
PATCHverb is the most common for full resource updates. - D
The
GETverb is preferred for changing the state of a resource.
Correct answer
AThe
PUTverb is generally used for replacing or updating resources.Explanation
The
PUTHTTP verb is commonly used for updating existing resources. It typically replaces the entire resource with the new data provided. The example uses it to toggle acompletedstatus, which is a specific type of update. - A
- 24
How do you find the index of an element in an array based on a condition, as shown for updating a to-do?
- A
Use
array.indexOf(element.id === id)to get the index. - B
Iterate with
forEachand store the index manually. - C
Employ
array.findIndex(item => item.id === id)for the index. - D
Utilize
array.find(item => item.id === id).index()directly.
Correct answer
CEmploy
array.findIndex(item => item.id === id)for the index.Explanation
The
findIndex()method of arrays is used to find the index of the first element in the array that satisfies the provided testing function. This is suitable for locating a specific to-do by its ID to then update it by its index. - A
- 25
Which HTTP verb is used to remove a specific resource from the server?
- A
The
DELETEverb is specifically designed for deleting resources. - B
The
PURGEverb is utilized for permanent removal. - C
The
REMOVEverb is an alternative for resource deletion. - D
The
CLEARverb is dedicated to resource removal.
Correct answer
AThe
DELETEverb is specifically designed for deleting resources.Explanation
The
DELETEHTTP verb is the standard method used in RESTful APIs to request that the origin server delete the resource identified by the Request-URI. - A
- 26
How can an array of to-do items be updated to remove a specific item based on its ID?
- A
By assigning the array to
array.filter(todo => todo.id !== id). - B
By using
splice()on the original array directly. - C
By setting the element at the index to
nullorundefined. - D
By manually looping and removing the matching element.
Correct answer
ABy assigning the array to
array.filter(todo => todo.id !== id).Explanation
To remove an item from an array and get a new array without that item, the
filter()method is very effective. It creates a new array containing all elements for which the provided callback function returnstrue. By filtering fortodo.id !== id, all items except the one with the specified ID are kept. - A
- 27
What is the primary benefit of grouping routes into separate files (e.g.,
routes/todos.js)?- A
It improves code organization and maintainability for large applications.
- B
It enforces stricter security protocols for API endpoints.
- C
It allows for faster server startup times.
- D
It enables automatic data validation for all route parameters.
Correct answer
AIt improves code organization and maintainability for large applications.
Explanation
Grouping routes into separate files (like
routes/todos.js) helps in organizing the codebase, especially as an application grows. This makes theindex.jsor main application file cleaner and improves maintainability by separating concerns. - A
- 28
What is used in
routes/todos.jsinstead ofappto define individual routes within a modular file?- A
The
routerobject obtained fromexpress.Router(). - B
The
serverobject from the main application file. - C
A
moduleobject that is implicitly available. - D
An
Endpointinstance specifically for this file.
Correct answer
AThe
routerobject obtained fromexpress.Router().Explanation
When structuring routes modularly,
express.Router()is used to create a new router object. This object then behaves like a mini-application, allowing you to define route handlers usingrouter.get(),router.post(), etc., instead ofapp.get(),app.post()directly. - A
- 29
How do you make routes defined in a modular
routeravailable to the main Expressapp?- A
By directly assigning the router to
app.routesproperty. - B
By including the router's file path in the
package.json. - C
By calling
app.mount(router)with the router object. - D
By importing the router with
require()and then usingapp.use().
Correct answer
DBy importing the router with
require()and then usingapp.use().Explanation
To integrate modular routers into the main Express application, you use
app.use(). The first parameter toapp.use()can be a base path, and the second is the router object imported viarequire(), making its routes available under the specified path. - A
- 30
What is the function of the optional first string parameter in
app.use('/todos', todoRoutes)?- A
It defines a unique name for the middleware or router being used.
- B
It sets a common base path for all routes defined within
todoRoutes. - C
It specifies the exact file path where the router is located.
- D
It limits the router to only handle requests with a query parameter 'todos'.
Correct answer
BIt sets a common base path for all routes defined within
todoRoutes.Explanation
When
app.use()is called with a path as its first argument (e.g.,'/todos'), it means that all routes defined within thetodoRoutesrouter will be prefixed with/todos. This creates a common base path for the group of routes. - A
- 31
What does 'middleware' refer to in the context of Express.js?
- A
It is a database layer that sits between the application and data storage.
- B
It is a templating engine used for rendering dynamic HTML content.
- C
It is a tool for managing application state across different components.
- D
It is code that executes before or after a request reaches a route handler.
Correct answer
DIt is code that executes before or after a request reaches a route handler.
Explanation
Middleware functions are functions that have access to the request object (
req), the response object (res), and thenextmiddleware function in the application’s request-response cycle. They can execute any code, make changes to the request and the response objects, end the request-response cycle, or call the next middleware in the stack.app.use(express.json())is a prime example. - A
- 32
Which parameter in a middleware function is used to pass control to the next middleware or route handler?
- A
The
passparameter transfers control immediately. - B
The
finishparameter is invoked to proceed. - C
The
continueparameter signals the next step. - D
The
nextparameter is called to move forward in the chain.
Correct answer
DThe
nextparameter is called to move forward in the chain.Explanation
Middleware functions in Express take a third argument,
next. Callingnext()within a middleware function passes control to the next middleware function in the stack, or if there are no more middleware functions, to the route handler. - A
- 33
How do you access custom data sent within the HTTP request headers in an Express middleware?
- A
By calling
req.query.headerNamefor the header data. - B
By checking
req.params.headerNamefor the header value. - C
By accessing
req.header('headerName')orreq.headers['headerName']. - D
By using
req.body.headerNameto get the value.
Correct answer
CBy accessing
req.header('headerName')orreq.headers['headerName'].Explanation
The
req.header()method (or direct accessreq.headers['header-name']) is used to retrieve values from the HTTP request headers. The example showsreq.header('authenticated')to check for an authentication status. - A
- 34
What HTTP status code typically indicates that a client's request is forbidden due to insufficient authorization?
- A
Status code 403 (Forbidden) signifies a lack of permission.
- B
Status code 400 (Bad Request) is used for forbidden access.
- C
Status code 500 (Internal Server Error) indicates forbidden action.
- D
Status code 200 (OK) implies unauthorized access.
Correct answer
AStatus code 403 (Forbidden) signifies a lack of permission.
Explanation
The HTTP status code 403 Forbidden indicates that the server understood the request but refuses to authorize it. This typically means the client does not have the necessary permissions for the resource.
- A

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