Unit 2 - Practice Quiz

INT222 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is Express.js primarily known as?

Introducing Express Easy
A. A database management system
B. A JavaScript runtime environment
C. A front-end JavaScript library
D. A web application framework for Node.js

2 Which command is used to install Express.js into a Node.js project using npm?

Installing Express Easy
A. npm install express
B. npm start express
C. npm get express
D. node install express

3 Which HTTP method is designed to be idempotent and is primarily used for retrieving data from a server?

GET and POST Easy
A. PUT
B. DELETE
C. POST
D. GET

4 In an Express application, which method is most commonly used to handle form submissions that create a new resource?

GET and POST Easy
A. app.send()
B. app.post()
C. app.get()
D. app.fetch()

5 What is the primary purpose of express.Router?

express.Router Easy
A. To serve static files like CSS and images.
B. To connect to a database.
C. To group route handlers for a particular path or resource.
D. To automatically validate all incoming requests.

6 What is the main function of the express-validator library?

express validator Easy
A. To validate and sanitize data from incoming requests.
B. To test the speed of API endpoints.
C. To automatically handle all server errors.
D. To check for JavaScript syntax errors.

7 In Express, an error-handling middleware function is defined with a specific signature. How many arguments does it have?

Error Handling Easy
A. Two: req, res
B. One: req
C. Four: err, req, res, next
D. Three: req, res, next

8 Which built-in Node.js module is used to create HTTP servers and clients without any external frameworks?

Introduction to HTTP module Easy
A. path
B. fs
C. http
D. express

9 Which method is called on the Node.js http module to create a new HTTP server instance?

Setting up a basic HTTP server Easy
A. http.initialize()
B. http.startServer()
C. http.new()
D. http.createServer()

10 In the callback function of http.createServer((req, res) => { ... }), what does the req object represent?

Understanding Request, Response and Server Objects Easy
A. The server configuration.
B. A required library.
C. The incoming client request.
D. The server's response.

11 Which method on the response object (res) is used to signal that the entire response (headers and body) has been sent?

Understanding Request, Response and Server Objects Easy
A. res.send()
B. res.finish()
C. res.end()
D. res.close()

12 When using the native Node.js http module, which property of the request object is typically checked to implement basic routing?

Implementing basic routing Easy
A. req.route
B. req.path
C. req.url
D. req.destination

13 Which HTTP status code signifies that a request was successful?

Setting response headers and status codes Easy
A. 404
B. 500
C. 301
D. 200

14 In Node's native http module, how do you set the HTTP status code of a response?

Setting response headers and status codes Easy
A. By setting the res.statusCode property.
B. By setting the res.code property.
C. By calling res.setHeader('Status', 200).
D. By calling res.setStatus(200).

15 Which architectural style is characterized by a single, large, and unified codebase for the entire application?

Microservices vs. Monoliths Easy
A. Microservices
B. Peer-to-Peer
C. Serverless
D. Monolith

16 What is a primary advantage of a microservices architecture?

Microservices vs. Monoliths Easy
A. Simpler initial setup and deployment.
B. Easier debugging across the entire application.
C. Services can be developed, deployed, and scaled independently.
D. Reduced network communication overhead.

17 After creating a server object with http.createServer(), which method must be called to make the server start listening for connections?

Implementing HTTP Services in Node.JS Easy
A. server.run()
B. server.listen()
C. server.connect()
D. server.start()

18 What is middleware in the context of Express.js?

Introducing Express Easy
A. A specific version of Node.js.
B. A type of database.
C. A tool for managing front-end assets.
D. Functions that have access to the request and response objects, and can modify them or end the request-response cycle.

19 How would you set the Content-Type header to application/json in an Express response?

Setting response headers and status codes Easy
A. res.json.type('application/json')
B. res.set('Content-Type', 'application/json')
C. res.send({ type: 'json' })
D. res.type = 'application/json'

20 What is the purpose of the res.json() method in Express?

Understanding Request, Response and Server Objects Easy
A. To read a JSON file from the server's disk.
B. To send a JSON response and automatically set the Content-Type header.
C. To validate if an incoming request body is valid JSON.
D. To parse a JSON string into a JavaScript object.

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?

Introducing Express Medium
A. Middleware pattern
B. Controller pattern
C. Singleton pattern
D. Observer pattern

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+)?

Installing Express Medium
A. It globally installs Express for all projects on the system.
B. It saves the package as a development dependency in package.json.
C. It is required to download the package from the npm registry.
D. It is redundant as npm v5+ saves dependencies by default.

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?

GET and POST Medium
A. req.body.bookId
B. req.params.bookId
C. req.query.bookId
D. 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?

GET and POST Medium
A. express.urlencoded({ extended: true })
B. express.text()
C. express.json()
D. 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?

express.Router Medium
A. const userRoutes = require('./routes/users'); app.mount('/api/users', userRoutes);
B. const userRoutes = require('./routes/users'); app.get('/api/users', userRoutes);
C. const userRoutes = require('./routes/users'); app.use('/api/users', userRoutes);
D. 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?

express.Router Medium
A. It improves the performance of all routes in the application.
B. It automatically handles errors for all routes within that router.
C. It allows the middleware to be scoped and applied only to the group of routes defined in that router.
D. It is the only way to handle asynchronous middleware.

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?

express validator Medium
A. check('email').isEmail().toLowerCase()
B. body('email').isEmail().sanitize().toLowerCase()
C. body('email').isEmail().normalizeEmail()
D. 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?

express validator Medium
A. The next() function will automatically be called with an error object containing the validation failures.
B. The application automatically throws an error and sends a 400 response.
C. Check if (req.hasErrors) { res.status(400).send(req.errors) }.
D. Import 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?

Error Handling Medium
A. It must be named errorHandler.
B. It must use res.send() instead of res.json().
C. It has a specific function signature with four arguments: (err, req, res, next).
D. It must be defined after all other 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?
}
});

Error Handling Medium
A. next(error);
B. throw error;
C. next();
D. res.status(500).send(error);

31 When would you choose to use Node.js's native http module directly over a framework like Express?

Introduction to HTTP module Medium
A. For building a very lightweight, high-performance server with minimal overhead and full control over the request/response lifecycle.
B. When you want built-in support for template engines like Pug or EJS.
C. For building complex, multi-page web applications with database integration.
D. When you need a high-level abstraction for routing and middleware.

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

Setting up a basic HTTP server Medium
A. It creates the server object and defines the request handler logic.
B. It parses the incoming HTTP request from the client.
C. It sends an HTTP response back to the client.
D. It binds the server to a specific network port and IP address, and starts listening for incoming connections.

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?

Understanding Request, Response and Server Objects Medium
A. request.method
B. request.headers['method']
C. request.type
D. 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?

Understanding Request, Response and Server Objects Medium
A. response.close()
B. response.write()
C. response.send()
D. 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);

Implementing basic routing Medium
A. req.pathname
B. req.path
C. req.route
D. 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?

Setting response headers and status codes Medium
A. Status 200; res.statusCode = 200;
B. Status 202; res.statusCode = 202;
C. Status 201; res.statusCode = 201;
D. Status 204; 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?

Setting response headers and status codes Medium
A. res.setHeader('Content-Type', 'application/json');
B. res.writeHeader('Content-Type', 'application/json');
C. res.headers['Content-Type'] = 'application/json';
D. 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?

Microservices vs. Monoliths Medium
A. Database schemas can be updated for all services simultaneously in a single deployment.
B. A change to a single service (e.g., the payment service) can be deployed without redeploying the entire application.
C. It simplifies the initial development and deployment process for new projects.
D. The entire application must be deployed at once, ensuring consistency.

39 What is a significant challenge or trade-off when moving from a monolithic architecture to a microservices architecture?

Microservices vs. Monoliths Medium
A. Reduced ability to use different technology stacks for different services.
B. Slower development speed due to smaller, more focused teams.
C. Decreased fault tolerance, as a failure in one service always brings down the entire application.
D. Increased complexity in managing distributed data and ensuring transactional consistency.

40 In the context of team organization, what principle, often associated with microservices, suggests that software architecture and team structure should mirror each other?

Microservices vs. Monoliths Medium
A. The CAP Theorem
B. The Law of Demeter
C. The Single Responsibility Principle
D. Conway's Law

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?

Error Handling Hard
A. Simply throw err;
B. next(err);
C. There is no way to pass this error; the process will crash.
D. 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?

express.Router Hard
A. Only Child Route
B. Parent Middleware, then Child Route
C. Only Parent Middleware
D. 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?

Understanding Request, Response and Server Objects Hard
A. The TCP window size mechanism, which automatically throttles the connection.
B. The Express res.pipe() method internally chunks the data into small, memory-safe segments before sending.
C. The server automatically compresses the data stream, reducing its memory footprint before sending.
D. Node.js streams' built-in backpressure mechanism, where 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?

Microservices vs. Monoliths Hard
A. The Saga pattern, where the Order Service initiates a compensating transaction to cancel the order upon payment failure.
B. The Circuit Breaker pattern to isolate the payment service failure.
C. API Composition, where a client-side script coordinates the two service calls.
D. Two-Phase Commit (2PC) using a central transaction coordinator.

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?

express-validator Hard
A. .custom(async (value, { req }) => { const user = await User.findOne({ username: value }); return !user; })
B. .custom(async (value, { req }) => { const user = await User.findOne({ username: value }); if (user) { throw new Error('Username already in use'); } })
C. .custom((value, { req }) => { User.findOne({ username: value }).then(user => { if (user) return Promise.reject('Username taken'); }); })
D. .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?

Setting response headers and status codes Hard
A. 201 Created for the first, 200 OK for the second.
B. 201 Created for the first, 409 Conflict for the second.
C. 204 No Content for both responses.
D. 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?

Introduction to HTTP module Hard
A. server.headersTimeout
B. server.timeout
C. server.keepAliveTimeout
D. 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?

GET and POST Hard
A. undefined, because the Content-Length header is typically zero for GET requests, so the middleware doesn't attempt to read the body.
B. The parsed JSON object, because express.json() middleware parses all incoming JSON bodies regardless of the HTTP method.
C. An empty object {}, because the express.json() middleware is triggered but ignores the body for GET requests by default.
D. The raw string of the body, because 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?

Implementing basic routing Hard
A. 1. Use path.normalize(). 2. Use decodeURIComponent().
B. 1. Use url.parse(). 2. Check for '..' or '%2f' with a regular expression and reject if found.
C. 1. Use decodeURIComponent(). 2. Use path.normalize().
D. 1. Split the path by '/'. 2. Manually resolve '..' segments. 3. Join the path.

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?

express.Router Hard
A. The param handler will not run because /profile makes the parameter match ambiguous.
B. Only the /:id route will match because it is defined first; the second route is ignored.
C. An error occurs because two routes use the same parameter id.
D. The 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?

Microservices vs. Monoliths Hard
A. All database writes must use a two-phase commit protocol to ensure consistency.
B. Inter-service communication must be synchronous (e.g., direct REST calls) to ensure immediate data consistency.
C. The system must use a globally distributed, strongly consistent database like Google Spanner.
D. The system will return stale data from a service's local cache or replica during a network partition, achieving 'eventual consistency'.

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?

Setting up a basic HTTP server Hard
A. It prevents the server from accepting new connections and executes the callback immediately, while existing connections may continue.
B. It sends a 'connection: close' header to all active clients, waits for them to disconnect, and then executes the callback.
C. It immediately terminates all existing connections and then executes the callback.
D. It stops the server from accepting new connections and executes the callback only after all existing connections have been closed.

53 Given the following express-validator chain on an input string " <IMG SRC=j&#X41vascript:alert('XSS');> ":

javascript
body('comment').trim().escape().toLowerCase()

What will the final sanitized value of the comment field be?

express-validator Hard
A. &lt;img src=j&amp;#x41vascript:alert(&#x27;xss&#x27;);&gt;
B. <img src=j&#x41vascript:alert('xss');>
C. &lt;img src=j&amp;#x45;vascript:alert('xss');&gt;
D. &lt;img src=javascript:alert(&#x27;xss&#x27;);&gt;

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?

Understanding Request, Response and Server Objects Hard
A. res.end will throw an error if given a Buffer, as it only accepts strings.
B. There is no difference; res.send is just an alias for res.end.
C. 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.
D. 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?

Introducing Express Hard
A. middlewareA -> middlewareB -> handlerH -> errorHandlerE
B. middlewareA -> middlewareB -> errorHandlerE
C. middlewareA -> middlewareB
D. 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?

Installing Express Hard
A. Only one version of Express, likely the highest compatible version (e.g., 4.17.3), will be installed at the top level of node_modules, and both libraries will be forced to use it.
B. NPM will prompt the user to choose a version of Express to resolve the conflict.
C. The highest version satisfying ^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.
D. NPM will throw an 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?

GET and POST Hard
A. app.use(express.urlencoded({ nested: true }))
B. app.use(express.urlencoded({ extended: false }))
C. app.use(express.urlencoded({ extended: true }))
D. 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?

Implementing HTTP Services in Node.JS Hard
A. Building a server-side rendered website with a complex templating engine and session management.
B. Building a simple static file server for a personal blog.
C. Building a complex REST API with authentication, validation, and multiple endpoints.
D. Building a high-performance, special-purpose reverse proxy that only needs to inspect one header and stream the request/response with minimal overhead.

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?

Setting response headers and status codes Hard
A. A 200 OK status with the full resource body and the ETag: "xyz123" header.
B. A 412 Precondition Failed status with an empty body.
C. A 204 No Content status with an empty body.
D. A 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)?

Error Handling Hard
A. Express cannot handle errors from synchronous functions; they must always be handled with try...catch.
B. Synchronous errors are automatically caught by Express and passed to error-handling middleware, while errors in raw async callbacks are not caught and will crash the process unless explicitly passed to next().
C. Asynchronous errors are automatically caught, but synchronous errors will crash the process unless wrapped in a try...catch block.
D. Both synchronous and asynchronous errors are automatically caught and passed to error-handling middleware.