Unit 2 - Practice Quiz
1 What is Express.js primarily known as?
2 Which command is used to install Express.js into a Node.js project using npm?
npm install express
npm start express
npm get express
node install express
3 Which HTTP method is designed to be idempotent and is primarily used for retrieving data from a server?
4 In an Express application, which method is most commonly used to handle form submissions that create a new resource?
app.send()
app.post()
app.get()
app.fetch()
5
What is the primary purpose of express.Router?
6
What is the main function of the express-validator library?
7 In Express, an error-handling middleware function is defined with a specific signature. How many arguments does it have?
req, res
req
err, req, res, next
req, res, next
8 Which built-in Node.js module is used to create HTTP servers and clients without any external frameworks?
path
fs
http
express
9
Which method is called on the Node.js http module to create a new HTTP server instance?
http.initialize()
http.startServer()
http.new()
http.createServer()
10
In the callback function of http.createServer((req, res) => { ... }), what does the req object represent?
11
Which method on the response object (res) is used to signal that the entire response (headers and body) has been sent?
res.send()
res.finish()
res.end()
res.close()
12
When using the native Node.js http module, which property of the request object is typically checked to implement basic routing?
req.route
req.path
req.url
req.destination
13 Which HTTP status code signifies that a request was successful?
404
500
301
200
14
In Node's native http module, how do you set the HTTP status code of a response?
res.statusCode property.
res.code property.
res.setHeader('Status', 200).
res.setStatus(200).
15 Which architectural style is characterized by a single, large, and unified codebase for the entire application?
16 What is a primary advantage of a microservices architecture?
17
After creating a server object with http.createServer(), which method must be called to make the server start listening for connections?
server.run()
server.listen()
server.connect()
server.start()
18 What is middleware in the context of Express.js?
19
How would you set the Content-Type header to application/json in an Express response?
res.json.type('application/json')
res.set('Content-Type', 'application/json')
res.send({ type: 'json' })
res.type = 'application/json'
20
What is the purpose of the res.json() method in Express?
Content-Type header.
21 An Express application's request-response cycle is primarily managed by a sequence of functions that have access to the request object, the response object, and a function to pass control to the next function in the sequence. What is this architectural pattern called?
22
When initializing a new Node.js project, you run npm install express --save. What is the primary significance of the --save flag in modern versions of npm (v5+)?
package.json.
23
Consider the following Express route: app.get('/users/:userId/books/:bookId', (req, res) => { ... });. How would you access the value of bookId from a request to /users/101/books/5432?
req.body.bookId
req.params.bookId
req.query.bookId
req.headers['bookId']
24
To correctly parse a URL-encoded form submission from a POST request in an Express application, which built-in middleware is required?
express.urlencoded({ extended: true })
express.text()
express.json()
express.static('public')
25
You are modularizing your Express application. You have created a separate file routes/users.js for user-related routes. How would you correctly mount this router in your main app.js file so that a route defined as router.get('/profile', ...) in users.js is accessible at /api/users/profile?
const userRoutes = require('./routes/users'); app.mount('/api/users', userRoutes);
const userRoutes = require('./routes/users'); app.get('/api/users', userRoutes);
const userRoutes = require('./routes/users'); app.use('/api/users', userRoutes);
const userRoutes = require('./routes/users'); app.use(userRoutes);
26
What is a key advantage of applying middleware directly to an express.Router instance instead of the main app instance?
27
Using express-validator, you want to validate that an email field in the request body is a valid email format and then convert it to lowercase. Which of the following validation chains achieves this?
check('email').isEmail().toLowerCase()
body('email').isEmail().sanitize().toLowerCase()
body('email').isEmail().normalizeEmail()
check('email').isEmail().then(email => email.toLowerCase())
28
After running a set of express-validator checks, how do you typically access the validation errors and respond to the client if any exist?
next() function will automatically be called with an error object containing the validation failures.
if (req.hasErrors) { res.status(400).send(req.errors) }.
validationResult, call validationResult(req), and if the result is not empty, send a 400 response with the errors.
29 What is the defining characteristic of a custom error-handling middleware function in Express that distinguishes it from regular middleware?
errorHandler.
res.send() instead of res.json().
(err, req, res, next).
app.use() and route calls.
30
In an Express route handler, you have an asynchronous operation that might fail. What is the correct way to trigger the custom error-handling middleware from within a catch block?
javascript
app.get('/data', async (req, res, next) => {
try {
const data = await someAsyncOperationThatMightFail();
res.json(data);
} catch (error) {
// How to trigger the error handler?
}
});
next(error);
throw error;
next();
res.status(500).send(error);
31
When would you choose to use Node.js's native http module directly over a framework like Express?
32
Analyze the following code snippet using the native http module. What is the primary function of the server.listen method?
javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running...');
});
33
In a server created with the native Node.js http module, which property of the request object would you inspect to determine the HTTP method (e.g., GET, POST) of an incoming request?
request.method
request.headers['method']
request.type
request.action
34
Which method of the response object in the native http module is essential for signaling that the response is complete and the message body has been fully sent?
response.close()
response.write()
response.send()
response.end()
35
Given a basic HTTP server in Node.js, which property of the request object is most commonly used to implement simple routing?
javascript
const http = require('http');
http.createServer((req, res) => {
// Which req property is used here for routing?
if (req.??? === '/about') {
res.end('About Page');
} else {
res.end('Home Page');
}
}).listen(3000);
req.pathname
req.path
req.route
req.url
36
You are creating a REST API endpoint for creating a new user. Upon successful creation, what is the most semantically correct HTTP status code to return, and how would you set it using the native http module's response object?
res.statusCode = 200;
res.statusCode = 202;
res.statusCode = 201;
res.statusCode = 204;
37
How do you set the Content-Type header to application/json for a response in a server built with the native Node.js http module?
res.setHeader('Content-Type', 'application/json');
res.writeHeader('Content-Type', 'application/json');
res.headers['Content-Type'] = 'application/json';
res.contentType = 'application/json';
38 A development team is building a large e-commerce platform. They are considering a microservices architecture. What is a primary advantage of this approach concerning independent deployment?
39 What is a significant challenge or trade-off when moving from a monolithic architecture to a microservices architecture?
40 In the context of team organization, what principle, often associated with microservices, suggests that software architecture and team structure should mirror each other?
41
Consider the following Express route handler:
javascript
app.get('/data', (req, res, next) => {
setTimeout(() => {
try {
throw new Error('Async Error!');
} catch (err) {
// What should be placed here to correctly pass the error to Express?
}
}, 100);
});
app.use((err, req, res, next) => {
console.log('Error Handler Called');
res.status(500).send(err.message);
});
To ensure the custom error-handling middleware is invoked for the error thrown inside the setTimeout, what is the only correct implementation for the catch block?
throw err;
next(err);
return err;
42
You have a nested router setup as follows:
javascript
const express = require('express');
const app = express();
const parentRouter = express.Router();
const childRouter = express.Router();
parentRouter.use((req, res, next) => {
console.log('Parent Middleware');
next();
});
childRouter.get('/data', (req, res, next) => {
console.log('Child Route');
res.send('data');
});
// How are the routers mounted?
app.use('/api', parentRouter);
parentRouter.use('/v1', childRouter);
When a request is made to GET /api/v1/data, what will be the order of the console logs?
Child Route
Parent Middleware, then Child Route
Parent Middleware
Child Route, then Parent Middleware
43
When piping a large readable stream (e.g., from fs.createReadStream) to the res object in an Express application for a client with a very slow network connection, what mechanism prevents the server's memory from being exhausted by buffering the entire file?
res.pipe() method internally chunks the data into small, memory-safe segments before sending.
res.write() returns false when the kernel buffer is full, causing the readable stream to pause.
44
In a microservices architecture, an operation to create a customer order requires two distinct actions: 1) The Order Service creates an order record. 2) The Payment Service processes the payment. If the payment processing fails, the order must be cancelled to maintain data consistency. Which design pattern is most suitable for managing this distributed transaction?
45
You are creating a custom asynchronous validator with express-validator to check if a username is unique by querying a database. Which implementation is correct for the .custom() validator?
.custom(async (value, { req }) => { const user = await User.findOne({ username: value }); return !user; })
.custom(async (value, { req }) => { const user = await User.findOne({ username: value }); if (user) { throw new Error('Username already in use'); } })
.custom((value, { req }) => { User.findOne({ username: value }).then(user => { if (user) return Promise.reject('Username taken'); }); })
.custom(async (value, { req }) => { const user = await User.findOne({ username: value }); if (user) { return false; } return true; })
46
An API endpoint PUT /documents/123 is designed to be idempotent. A client sends a request for the first time, and the server creates the document. The client then sends the exact same PUT request again due to a network retry. What are the most semantically correct HTTP status codes for the server to return for the first and second responses, respectively?
201 Created for the first, 200 OK for the second.
201 Created for the first, 409 Conflict for the second.
204 No Content for both responses.
200 OK for the first, 304 Not Modified for the second.
47
When using Node.js's native http module, you observe that your server is keeping idle TCP connections open for a long time, consuming resources. To mitigate this, you want to set a timeout specifically for idle sockets that are part of the keep-alive pool. Which property of the http.Server instance should you configure?
server.headersTimeout
server.timeout
server.keepAliveTimeout
server.requestTimeout
48
A developer sends a GET request to an Express server with a JSON payload in the request body. The server is configured with app.use(express.json()). What will be the value of req.body inside the route handler, and why?
undefined, because the Content-Length header is typically zero for GET requests, so the middleware doesn't attempt to read the body.
express.json() middleware parses all incoming JSON bodies regardless of the HTTP method.
{}, because the express.json() middleware is triggered but ignores the body for GET requests by default.
express.json() only works for POST, PUT, and PATCH requests.
49
When implementing routing using only the native Node.js http module, a request is received for the URL /api/users/../products/..%2fimages. To prevent path traversal attacks, what is the correct sequence of operations to safely resolve the intended path?
path.normalize(). 2. Use decodeURIComponent().
url.parse(). 2. Check for '..' or '%2f' with a regular expression and reject if found.
decodeURIComponent(). 2. Use path.normalize().
50
Consider an Express router with a param handler and two routes:
javascript
const userRouter = express.Router();
userRouter.param('id', (req, res, next, id) => {
req.user = { id: id, name: 'Test User' };
console.log('Param handler called');
next();
});
userRouter.get('/:id', (req, res) => {
console.log('Get user by ID');
res.send(req.user);
});
userRouter.get('/:id/profile', (req, res) => {
console.log('Get user profile');
res.send(req.user.name + ' Profile');
});
If a request is made to GET /123/profile, what is the expected output and behavior?
param handler will not run because /profile makes the parameter match ambiguous.
/:id route will match because it is defined first; the second route is ignored.
id.
param handler runs, req.user is set, and the /:id/profile route is executed. Logs: 'Param handler called', 'Get user profile'.
51 In the context of the CAP theorem, if a Node.js-based microservices system prioritizes Availability (A) and Partition Tolerance (P), it must sacrifice strong Consistency (C). What is a common practical implication of this trade-off?
52
What is the primary function of the server.close(callback) method on a Node.js http.Server instance, and when is the provided callback function executed?
53
Given the following express-validator chain on an input string " <IMG SRC=jAvascript:alert('XSS');> ":
javascript
body('comment').trim().escape().toLowerCase()
What will the final sanitized value of the comment field be?
<img src=j&#x41vascript:alert('xss');>
<img src=jAvascript:alert('xss');>
<img src=j&#x45;vascript:alert('xss');>
<img src=javascript:alert('xss');>
54
In an Express route handler, what is the most significant difference in behavior between res.end(myBuffer) and res.send(myBuffer) when myBuffer is a Node.js Buffer object?
res.end will throw an error if given a Buffer, as it only accepts strings.
res.send is just an alias for res.end.
res.send will automatically set the Content-Type header to application/octet-stream, while res.end will not set any headers and just send the raw buffer.
res.send performs asynchronous I/O while res.end is synchronous, blocking the event loop.
55
Consider an Express application with the following middleware and route handlers defined in order:
1. app.use(middlewareA)
2. app.use(middlewareB)
3. app.get('/route', handlerH)
4. app.use(errorHandlerE)
If middlewareB calls next(new Error('Auth failed')), which functions will be executed for an incoming request to GET /route?
middlewareA -> middlewareB -> handlerH -> errorHandlerE
middlewareA -> middlewareB -> errorHandlerE
middlewareA -> middlewareB
middlewareA -> middlewareB -> handlerH
56
Your package.json has two dependencies: lib-A which requires express: "^4.17.1" and lib-B which requires express: "~4.16.0". After running npm install, which statement most accurately describes the resulting node_modules directory structure?
node_modules, and both libraries will be forced to use it.
^4.17.1 will be installed at the top level of node_modules. A separate, nested copy of Express satisfying ~4.16.0 will be installed inside node_modules/lib-B/node_modules/express.
EPEERDEP error and installation will fail due to the conflict.
57
A web form POSTs data with nested field names like user[name]=Alice&user[address][city]=Wonderland. To have req.body parsed correctly into a nested object ({ user: { name: 'Alice', address: { city: 'Wonderland' } } }), how must the express.urlencoded middleware be configured?
app.use(express.urlencoded({ nested: true }))
app.use(express.urlencoded({ extended: false }))
app.use(express.urlencoded({ extended: true }))
app.use(express.urlencoded()) is sufficient as this is the default behavior.
58
For which of the following scenarios would using the native Node.js http module be significantly more advantageous than using the Express framework?
59
A client makes a conditional GET request for a resource, including the header If-None-Match: "xyz123". The server determines that the current version of the resource has an ETag of "xyz123". What is the most appropriate and efficient response the server should send?
200 OK status with the full resource body and the ETag: "xyz123" header.
412 Precondition Failed status with an empty body.
204 No Content status with an empty body.
304 Not Modified status with an empty body.
60
In Express, what is a key difference in how errors are handled when they are thrown inside a synchronous function (e.g., a route handler) versus inside an asynchronous operation that does not use promises chained to the original handler (e.g., a raw callback from fs.readFile)?
try...catch.
next().
try...catch block.