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 front-end JavaScript library
B. A JavaScript runtime environment
C. A web application framework for Node.js
D. A database management system

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 get express
C. npm start 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. POST
B. GET
C. DELETE
D. PUT

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.get()
B. app.post()
C. app.send()
D. app.fetch()

5 What is the primary purpose of express.Router?

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

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 check for JavaScript syntax errors.
C. To test the speed of API endpoints.
D. To automatically handle all server 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. Four: err, req, res, next
B. One: req
C. Two: req, res
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. fs
B. http
C. express
D. path

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. A required library.
B. The server configuration.
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.close()
C. res.finish()
D. res.end()

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.destination
B. req.url
C. req.route
D. req.path

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

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

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. Serverless
B. Monolith
C. Peer-to-Peer
D. Microservices

16 What is a primary advantage of a microservices architecture?

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

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 tool for managing front-end assets.
C. Functions that have access to the request and response objects, and can modify them or end the request-response cycle.
D. A type of database.

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.set('Content-Type', 'application/json')
B. res.send({ type: 'json' })
C. res.json.type('application/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 parse a JSON string into a JavaScript object.
B. To send a JSON response and automatically set the Content-Type header.
C. To read a JSON file from the server's disk.
D. To validate if an incoming request body is valid JSON.

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. Observer pattern
B. Singleton pattern
C. Middleware pattern
D. Controller 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 is required to download the package from the npm registry.
B. It is redundant as npm v5+ saves dependencies by default.
C. It saves the package as a development dependency in package.json.
D. It globally installs Express for all projects on the system.

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.params.bookId
B. req.body.bookId
C. req.headers['bookId']
D. req.query.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.text()
B. express.static('public')
C. express.json()
D. express.urlencoded({ extended: true })

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.use(userRoutes);
B. const userRoutes = require('./routes/users'); app.use('/api/users', userRoutes);
C. const userRoutes = require('./routes/users'); app.get('/api/users', userRoutes);
D. const userRoutes = require('./routes/users'); app.mount('/api/users', 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 allows the middleware to be scoped and applied only to the group of routes defined in that router.
B. It improves the performance of all routes in the application.
C. It automatically handles errors for all routes within 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. check('email').isEmail().then(email => email.toLowerCase())
D. body('email').isEmail().normalizeEmail()

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. Import validationResult, call validationResult(req), and if the result is not empty, send a 400 response with the errors.
B. The application automatically throws an error and sends a 400 response.
C. The next() function will automatically be called with an error object containing the validation failures.
D. Check if (req.hasErrors) { res.status(400).send(req.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 use res.send() instead of res.json().
B. It must be defined after all other app.use() and route calls.
C. It must be named errorHandler.
D. It has a specific function signature with four arguments: (err, req, res, next).

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();
B. res.status(500).send(error);
C. throw error;
D. next(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 complex, multi-page web applications with database integration.
B. For building a very lightweight, high-performance server with minimal overhead and full control over the request/response lifecycle.
C. When you want built-in support for template engines like Pug or EJS.
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 binds the server to a specific network port and IP address, and starts listening for incoming connections.
C. It parses the incoming HTTP request from the client.
D. It sends an HTTP response back to the client.

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.type
B. request.method
C. request.headers['method']
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.send()
C. response.write()
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.url
C. req.path
D. req.route

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 204; res.statusCode = 204;
B. Status 200; res.statusCode = 200;
C. Status 202; res.statusCode = 202;
D. Status 201; res.statusCode = 201;

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.contentType = 'application/json';
B. res.writeHeader('Content-Type', 'application/json');
C. res.headers['Content-Type'] = 'application/json';
D. res.setHeader('Content-Type', '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. A change to a single service (e.g., the payment service) can be deployed without redeploying the entire application.
B. The entire application must be deployed at once, ensuring consistency.
C. Database schemas can be updated for all services simultaneously in a single deployment.
D. It simplifies the initial development and deployment process for new projects.

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. Decreased fault tolerance, as a failure in one service always brings down the entire application.
C. Slower development speed due to smaller, more focused teams.
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 Single Responsibility Principle
C. Conway's Law
D. The Law of Demeter

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

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. Child Route, then Parent Middleware
B. Only Child Route
C. Parent Middleware, then Child Route
D. Only 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. Node.js streams' built-in backpressure mechanism, where res.write() returns false when the kernel buffer is full, causing the readable stream to pause.
D. The server automatically compresses the data stream, reducing its memory footprint before sending.

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. Two-Phase Commit (2PC) using a central transaction coordinator.
D. API Composition, where a client-side script coordinates the two service calls.

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

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, 409 Conflict for the second.
B. 200 OK for the first, 304 Not Modified for the second.
C. 204 No Content for both responses.
D. 201 Created for the first, 200 OK 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.timeout
B. server.headersTimeout
C. server.requestTimeout
D. server.keepAliveTimeout

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

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 url.parse(). 2. Check for '..' or '%2f' with a regular expression and reject if found.
B. 1. Use decodeURIComponent(). 2. Use path.normalize().
C. 1. Split the path by '/'. 2. Manually resolve '..' segments. 3. Join the path.
D. 1. Use path.normalize(). 2. Use decodeURIComponent().

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. Only the /:id route will match because it is defined first; the second route is ignored.
B. The param handler runs, req.user is set, and the /:id/profile route is executed. Logs: 'Param handler called', 'Get user profile'.
C. The param handler will not run because /profile makes the parameter match ambiguous.
D. An error occurs because two routes use the same parameter id.

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 will return stale data from a service's local cache or replica during a network partition, achieving 'eventual consistency'.
D. The system must use a globally distributed, strongly consistent database like Google Spanner.

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 sends a 'connection: close' header to all active clients, waits for them to disconnect, and then executes the callback.
B. It stops the server from accepting new connections and executes the callback only after all existing connections have been closed.
C. It immediately terminates all existing connections and then executes the callback.
D. It prevents the server from accepting new connections and executes the callback immediately, while existing connections may continue.

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. <img src=j&#x41vascript:alert('xss');>
B. &lt;img src=j&amp;#x45;vascript:alert('xss');&gt;
C. &lt;img src=javascript:alert(&#x27;xss&#x27;);&gt;
D. &lt;img src=j&amp;#x41vascript: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.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.
B. res.send performs asynchronous I/O while res.end is synchronous, blocking the event loop.
C. res.end will throw an error if given a Buffer, as it only accepts strings.
D. There is no difference; res.send is just an alias for res.end.

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. NPM will throw an EPEERDEP error and installation will fail due to the conflict.
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. 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.

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({ extended: false }))
B. app.use(express.urlencoded({ extended: true }))
C. app.use(express.urlencoded({ nested: 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 high-performance, special-purpose reverse proxy that only needs to inspect one header and stream the request/response with minimal overhead.
C. Building a complex REST API with authentication, validation, and multiple endpoints.
D. Building a simple static file server for a personal blog.

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 304 Not Modified status with an empty body.
B. A 204 No Content status with an empty body.
C. A 412 Precondition Failed status with an empty body.
D. A 200 OK status with the full resource body and the ETag: "xyz123" header.

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. Both synchronous and asynchronous errors are automatically caught and passed to error-handling middleware.
B. Asynchronous errors are automatically caught, but synchronous errors will crash the process unless wrapped in a try...catch block.
C. Express cannot handle errors from synchronous functions; they must always be handled with try...catch.
D. 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().