






















































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A services-oriented Node.js exam emphasizing microservices, APIs, authentication, testing frameworks, and production deployment. Students implement routing, inter-service communication, JWT/OAuth flows, CI pipelines, containerization, and performance monitoring.
Typology: Exams
1 / 94
This page cannot be seen from the preview
Don't miss anything!























































































Question 1. Which core Node.js module is used to create a low‑level HTTP server without any external dependencies? A) net B) http C) url D) fs Answer: B Explanation: The http module provides functions to create an HTTP server and handle requests/responses directly. Question 2. When initializing an HTTP server with http.createServer(), which callback signature is correct? A) (req, res) => {} B) (error, req, res) => {} C) (req) => {} D) (res) => {} Answer: A Explanation: The callback receives the incoming request object and the response object to handle the transaction. Question 3. Which of the following options can be passed to http.createServer() to set a custom timeout for incoming connections? A) { timeout: 5000 } B) { keepAlive: true } C) { maxHeadersCount: 1000 } D) { connectionTimeout: 5000 }
Answer: A Explanation: The timeout option defines the number of milliseconds of inactivity before the socket is closed. Question 4. To gracefully shut down a Node.js server, which method should be called? A) server.end() B) server.close() C) server.stop() D) server.disconnect() Answer: B Explanation: server.close() stops the server from accepting new connections and waits for existing connections to finish. Question 5. Which environment variable is conventionally used to define the listening port of a Node.js web service? A) HOST B) URL C) PORT D) NODE_ENV Answer: C Explanation: process.env.PORT is the standard way to read the port configuration from the environment. Question 6. In an Express application, which method is used to mount middleware that runs for every request? A) app.use()
B) 201 Created C) 202 Accepted D) 204 No Content Answer: B Explanation: 201 Created indicates that a new resource has been created and typically includes a Location header. Question 10. In a REST API, which status code best represents a request with malformed JSON in the body? A) 400 Bad Request B) 401 Unauthorized C) 403 Forbidden D) 422 Unprocessable Entity Answer: A Explanation: 400 Bad Request signals that the server cannot process the request due to client‑side syntax errors. Question 11. Which response header informs browsers to only communicate over HTTPS for the next 1 year? A) Content-Security-Policy B) Strict-Transport-Security C) X-Content-Type-Options D) X-Frame-Options Answer: B
Explanation: Strict-Transport-Security (STS) tells browsers to enforce HTTPS for the specified max-age. Question 12. Which third‑party library provides a convenient Promise‑based API for making HTTP requests from Node.js? A) request B) node-fetch C) axios D) http‑client Answer: C Explanation: axios returns Promises and supports async/await, making HTTP client code succinct. Question 13. When using node-fetch, which method extracts the JSON body from a response object? A) .json() B) .body() C) .parse() D) .toJSON() Answer: A Explanation: response.json() returns a Promise that resolves with the parsed JSON payload. Question 14. Which syntax correctly implements async/await for an HTTP GET request using axios? A) const data = await axios.get(url); B) await axios.get(url).then(data => data);
Question 17. In an Express route, how can you retrieve a URL parameter named id from the path /users/:id? A) req.query.id B) req.params.id C) req.body.id D) req.headers.id Answer: B Explanation: URL parameters are stored in req.params. Question 18. Which middleware would you use to parse URL‑encoded form data in an Express app? A) express.json() B) express.urlencoded({ extended: true }) C) express.text() D) express.raw() Answer: B Explanation: express.urlencoded() parses application/x-www-form-urlencoded bodies. Question 19. When validating request data with Joi, which method creates a schema that requires a string field email to be a valid email address? A) Joi.string().email() B) Joi.email().string() C) Joi.validate({ email: 'email' }) D) Joi.object({ email: Joi.email() }) Answer: A Explanation: Joi.string().email() defines a string that must match email format.
Question 20. Which of the following is a primary benefit of using parameterized queries with a SQL driver? A) Faster query execution B) Automatic caching of results C) Prevention of SQL injection attacks D) Simplified syntax for joins Answer: C Explanation: Parameterized queries separate code from data, eliminating the chance for malicious input to alter SQL structure. Question 21. In MongoDB, which method safely inserts a document while avoiding NoSQL injection? A) collection.insertOne(doc) with user data directly concatenated into a query string B) collection.find({ $where: userInput }) C) collection.insertOne(sanitizedDoc) after validation D) collection.update({ $eval: userInput }) Answer: C Explanation: Validating and sanitizing the document before insertion prevents malicious operators from being injected. Question 22. Which Node.js module is commonly used for executing shell commands, and therefore requires careful input sanitization? A) fs B) child_process C) crypto
A) cors B) helmet C) rate-limit D) express-validator Answer: B Explanation: helmet bundles middleware for CSP, HSTS, X‑Content‑Type‑Options, and more. Question 26. In a rate‑limiting middleware, what does the term “burst” usually refer to? A) Maximum concurrent connections B) Number of requests allowed in a short time window before throttling C) Size of the request payload D) Number of simultaneous database queries Answer: B Explanation: “Burst” defines the short‑term allowance of requests that can exceed the steady‑state limit. Question 27. Which HTTP method is typically used by browsers to perform a CORS pre‑flight request? A) GET B) POST C) OPTIONS D) HEAD Answer: C Explanation: The browser sends an OPTIONS request to check permitted methods and headers before the actual request.
Question 28. When configuring CORS in Express with the cors package, which option restricts access to the origin https://example.com? A) { origin: true } B) { origin: '*' } C) { origin: 'https://example.com' } D) { origin: false } Answer: C Explanation: Setting origin to a specific URL limits cross‑origin requests to that domain. Question 29. Which authentication scheme transmits a signed token that can be verified without server‑side session storage? A) Session cookies B) API keys C) OAuth 2.0 Authorization Code D) JSON Web Token (JWT) Answer: D Explanation: JWTs contain a payload and signature, allowing stateless verification. Question 30. In an Express route protected by JWT, which part of the request typically contains the token? A) req.body.token B) req.query.token C) req.headers.authorization D) req.cookies.token Answer: C
C) tls.createServer({ key, cert }, app).listen(443); D) express.createSecureServer({ key, cert }, app).listen(443); Answer: A Explanation: https.createServer requires TLS credentials (key and cert) and returns a secure server instance. Question 34. Which HTTP status code indicates that the client must authenticate to gain network access? A) 401 Unauthorized B) 403 Forbidden C) 407 Proxy Authentication Required D) 511 Network Authentication Required Answer: D Explanation: 511 is defined for situations where network authentication (e.g., captive portals) is required. Question 35. In Express, which method can be used to define a route that handles all HTTP verbs for a given path? A) app.all() B) app.use() C) app.route() D) app.any() Answer: A Explanation: app.all(path, handler) registers the handler for every HTTP method matching the path.
Question 36. Which of the following is NOT a valid way to send a JSON response in Express? A) res.json({ success: true }); B) res.send({ success: true }); C) res.end(JSON.stringify({ success: true })); D) res.render({ success: true }); Answer: D Explanation: res.render is used for templating engines, not for sending raw JSON. Question 37. When using express.Router(), what is the purpose of router.use(middleware)? A) Attach middleware only to POST routes B) Register middleware that runs for every route defined on that router C) Replace the router’s request handler completely D) Export the router as a module Answer: B Explanation: router.use adds middleware to the router’s stack, affecting all subsequent routes. Question 38. Which Node.js feature allows you to listen for an event when a request body has been fully received? A) request.on('data') and request.on('end') B) request.once('finish') C) request.on('close') D) request.on('error') Answer: A Explanation: The data event provides chunks; the end event signals completion.
Answer: A Explanation: The schema explicitly enforces integer type and range constraints. Question 42. Which Express middleware would you use to enable gzip compression for responses? A) express.static() B) compression() from the compression package C) helmet.compress() D) express.compress() Answer: B Explanation: The compression package provides middleware that automatically gzips responses. Question 43. Which of the following is a common technique to prevent HTTP Parameter Pollution (HPP) in an Express application? A) Using app.set('trust proxy', true) B) Limiting the number of parameters parsed by querystring C) Enforcing a whitelist of allowed query parameters via validation D) Disabling req.body parsing Answer: C Explanation: Validating and whitelisting expected parameters ensures extra duplicate keys are rejected. Question 44. In a micro‑service architecture, which pattern best describes a service that aggregates data from multiple downstream services before responding to the client? A) Service Mesh
B) API Gateway C) Event Sourcing D) Circuit Breaker Answer: B Explanation: An API Gateway acts as a façade that can combine results from several services. Question 45. Which Node.js core module provides utilities for creating readable and writable streams, often used for handling large file uploads? A) fs B) stream C) buffer D) crypto Answer: B Explanation: The stream module defines the API for handling streaming data. Question 46. When using express-validator, which function runs the validation chain and returns any errors? A) validationResult(req) B) check(req) C) sanitize(req) D) validate(req) Answer: A Explanation: validationResult(req) extracts the result of the previously defined validation chain.
Explanation: JSON.parse throws on invalid JSON; wrapping it in try/catch allows graceful handling. Question 50. Which of the following best describes the purpose of the helmet.referrerPolicy() middleware? A) Set the Referrer-Policy header to control how much referrer information is sent with requests B) Block all incoming referrer headers C) Encrypt the referrer URL D) Remove the Referrer header entirely Answer: A Explanation: The middleware sets the Referrer-Policy header, influencing browser behavior. Question 51. In an Express error‑handling middleware, which signature distinguishes it from regular middleware? A) (err, req, res, next) B) (req, res, next) C) (error, request, response) D) (req, res) Answer: A Explanation: Error‑handling middleware has four parameters; the first is the error object. Question 52. Which of the following is the most secure way to store a private RSA key used for signing JWTs in a Node.js application? A) Hard‑code it in the source file B) Store it in an environment variable
C) Keep it in a plain text file in the project root D) Save it in a public GitHub repository Answer: B Explanation: Environment variables keep secrets out of source control and can be managed securely. Question 53. When using the fetch API in Node.js (via node-fetch), which option disables SSL certificate verification? A) { rejectUnauthorized: false } B) { strictSSL: false } C) { agent: new https.Agent({ rejectUnauthorized: false }) } D) { insecure: true } Answer: C Explanation: Providing an HTTPS agent with rejectUnauthorized: false disables certificate verification, though it should be avoided in production. Question 54. Which HTTP header can be used by a server to indicate that a response should be interpreted as a downloadable file? A) Content-Type: application/octet-stream B) Content-Disposition: attachment; filename="data.json" C) Cache-Control: no-cache D) Accept-Ranges: bytes Answer: B Explanation: Content-Disposition: attachment prompts browsers to download rather than display the content.