Express.js Comprehensive Quiz & Projects
30 questions on Express.js Tutorial.
Question 1: In Express.js, what does the next() function do inside a middleware function?
- A. Renders the next HTML template configured in the router.
- B. Terminates the current request and returns a 200 OK response.
- C. Passes execution control to the next middleware function in the request-response stack. β (correct answer)
- D. Redirects the client's browser to the next sequential route.
Explanation: If the current middleware function does not end the request-response cycle, it must call next() to pass control.
Question 2: What is the correct signature for an Express error-handling middleware function?
- A. function(req, res, next)
- B. function(err, req, res, next) β (correct answer)
- C. function(err, req, res)
- D. function(req, res, err)
Explanation: Error-handling middleware functions always take four arguments: (err, req, res, next).
Question 3: In the Express route definition app.get('/users/:userId/books/:bookId'), how do you access the dynamic bookId param?
- A. req.body.bookId
- B. req.query.bookId
- C. req.params.bookId β (correct answer)
- D. req.headers.bookId
Explanation: Dynamic route segments prefixed with a colon are parsed into the req.params object.
Question 4: What happens if you omit calling next() or returning a response (like res.send()) in an Express middleware?
- A. Express will automatically throw a 504 Gateway Timeout error.
- B. The request will hang, and the client will wait until a browser timeout occurs. β (correct answer)
- C. Express will bypass the middleware and render the homepage.
- D. The node server will crash immediately due to a segmentation fault.
Explanation: If you do not call next() and do not send a response, the request is left hanging, causing timeouts.
Question 5: How does the Express Router module contribute to enterprise backend architecture?
- A. It provides built-in clustering for multi-threaded request routing.
- B. It automatically generates SQL schemas based on HTTP request payloads.
- C. It allows developers to modularize routing logic by creating isolated, mountable sub-routers. β (correct answer)
- D. It encrypts all incoming headers automatically using TLS.
Explanation: Router is an isolated instance of middleware and routes, enabling modular, clean directory structures.
Question 6: Which built-in middleware parses incoming requests with JSON payloads?
- A. express.static()
- B. express.json() β (correct answer)
- C. express.urlencoded()
- D. express.router()
Explanation: express.json() parses body streams, populating the req.body object with parsed data.
Question 7: What is the purpose of the express.static() middleware?
- A. Compressing Javascript asset codes.
- B. Serving static assets (images, CSS, JS files) directly from a specified directory. β (correct answer)
- C. Directing database connection queries.
- D. Caching views to memory.
Explanation: express.static(root) maps static requests to physical directories, serving them without dynamic route logic.
Question 8: In Express, how does error propagation work when using async/await route handlers?
- A. Errors are caught by Express automatically.
- B. You must wrap logic in try-catch and pass errors to next(err) manually (or use a wrapper library), as Express 4 does not catch async rejects. β (correct answer)
- C. Async errors crash the server node process instantly.
- D. Async errors are routed to the public/index.html file.
Explanation: Express 4 does not handle async errors. You must explicitly catch them and call next(err).
Question 9: Which method is used to define a route that responds to all HTTP methods?
- A. app.get()
- B. app.all() β (correct answer)
- C. app.use()
- D. app.any()
Explanation: app.all() maps the path across GET, POST, PUT, DELETE, and other methods.
Question 10: What is the difference between req.query and req.params?
- A. req.params holds variables parsed from route paths, while req.query holds key-value parameters parsed from the URL search query string. β (correct answer)
- B. req.query is encrypted, while req.params is plain text.
- C. req.params is populated on POST requests only.
- D. There is no difference; they are aliases.
Explanation: Params are path variables (e.g. /users/:id), while Query represents suffix keys (e.g. ?search=word).
Question 11: What is the security risk of using the default 'X-Powered-By' header in Express?
- A. It increases response latency.
- B. It advertises that the server is running Express, allowing attackers to target version-specific vulnerabilities. β (correct answer)
- C. It blocks CORS requests on Safari browsers.
- D. It interferes with SSL certificates.
Explanation: Disabling it (using app.disable('x-powered-by')) is a basic hardening practice.
Question 12: How do you start an Express application listening on port 3000?
- A. app.start(3000)
- B. app.listen(3000) β (correct answer)
- C. app.run(3000)
- D. app.port(3000)
Explanation: app.listen(port) starts a HTTP server listening on the defined port.
Question 13: How does CORS middleware function in Express?
- A. It blocks requests from the local server to external APIs.
- B. It appends the appropriate Access-Control-Allow-Origin headers to requests, enabling cross-domain AJAX requests. β (correct answer)
- C. It encrypts database communication.
- D. It compresses JSON payloads.
Explanation: CORS middleware sets response headers that tell browsers to allow queries from external web origins.
Question 14: What does app.set('view engine', 'pug') configure?
- A. The directory where HTML files are stored.
- B. The template renderer engine Express should use when rendering views using res.render(). β (correct answer)
- C. The local database driver.
- D. The compression codec for media files.
Explanation: It tells Express how to compile view files when res.render('view') is called.
Question 15: How do you send a JSON response in an Express route?
- A. res.writeJSON()
- B. res.json() β (correct answer)
- C. res.send(JSON.stringify())
- D. res.print()
Explanation: res.json() formats Javascript objects to JSON, sets the Content-Type header, and sends the response.
Question 16: What does the app.use() method do?
- A. Starts listening on a port.
- B. Mounts middleware function(s) globally or at specified paths in the application stack. β (correct answer)
- C. Defines database models.
- D. Restricts resource downloads.
Explanation: app.use() is the core method for injecting middlewares like parsers, routers, or loggers.
Question 17: What is the difference between res.send() and res.end()?
- A. res.send() is for JSON only, while res.end() works on HTML.
- B. res.send() automatically sets Content-Type and finishes the response, while res.end() finishes the request without sending data (often used to end a stream). β (correct answer)
- C. res.end() runs asynchronously, while res.send() runs synchronously.
- D. There is no difference.
Explanation: res.send() is a wrapper helper that computes headers and length, whereas res.end() is native Node HTTP end.
Question 18: Which object holds file uploads when using the multer middleware?
- A. req.body
- B. req.file (or req.files) β (correct answer)
- C. req.params
- D. req.uploads
Explanation: multer parses multipart/form-data payloads, populating files under the req.file attribute.
Question 19: What does res.redirect() do?
- A. Redirects database queries to a backup server.
- B. Sends a 302 HTTP redirect header to the client browser, forcing it to navigate to the specified path. β (correct answer)
- C. Replaces the current template file with index.html.
- D. Terminates the node process cleanly.
Explanation: res.redirect() instructs client browsers to issue a new GET request to a different address.
Question 20: Why should you use the helmet middleware package in an Express application?
- A. It speeds up payload parsing times.
- B. It automatically sets various security-focused HTTP headers to protect against common web vulnerabilities. β (correct answer)
- C. It compiles styles in the background.
- D. It prevents database injection.
Explanation: helmet secures Express apps by setting headers for XSS protection, MIME sniffing, and Clickjacking.
Question 21: How do you access cookies in an Express route handler?
- A. req.cookies β (correct answer)
- B. req.headers.cookies
- C. req.body.cookies
- D. req.getCookie()
Explanation: Utilizing the cookie-parser middleware populates the parsed cookies under req.cookies.
Question 22: Which Express method sets an HTTP status code for a response?
- A. res.code()
- B. res.status() β (correct answer)
- C. res.httpCode()
- D. res.setStatusCode()
Explanation: res.status(code) sets the status code, enabling chaining like res.status(201).json(data).
Question 23: What is the difference between app.param() and standard route wildcard parameters?
- A. app.param() runs a callback automatically whenever a specific parameter is present in any route path, useful for preloading models. β (correct answer)
- B. app.param() works only on local queries.
- C. Wildcard parameters cannot be accessed in middleware.
- D. app.param() encrypts the route slug.
Explanation: app.param() registers interceptor callbacks to modularize parameter resolution logic.
Question 24: What is Express.js?
- A. An ORM library for MySQL.
- B. A minimal and flexible Node.js web application framework providing features for web and mobile apps. β (correct answer)
- C. A package compiler for CSS.
- D. A server operating system.
Explanation: Express is a lightweight routing and middleware layer on top of native Node HTTP APIs.
Question 25: What does req.xhr return?
- A. The IP address of the server.
- B. A boolean indicating if the request was sent via AJAX (XMLHttpRequest or Fetch API). β (correct answer)
- C. The XML representation of the payload.
- D. The active controller file name.
Explanation: req.xhr is true if the request contains the 'X-Requested-With' header set to 'XMLHttpRequest'.
Question 26: How do you implement sub-routing in Express?
- A. Using app.group().
- B. By instantiating express.Router(), defining sub-routes on it, and mounting it in the app via app.use('/prefix', router). β (correct answer)
- C. Sub-routing is not supported in Express.
- D. By modifying package.json settings.
Explanation: Mountable routers allow clean module separations for different API sub-directories.
Question 27: Which package is standard for logging HTTP requests in an Express console?
- A. winston
- B. morgan β (correct answer)
- C. log4js
- D. console.log
Explanation: morgan is a popular request logging middleware that formats HTTP methods, status, and durations.
Question 28: Which method sets response header fields?
- A. res.header() or res.set() β (correct answer)
- B. res.setHeader()
- C. res.sendHeader()
- D. res.append()
Explanation: res.set(field, value) or res.set({ fields }) writes headers into the HTTP response.
Question 29: What is the purpose of the express-rate-limit middleware?
- A. It measures the network bandwidth speed.
- B. It limits repeated requests to public APIs, protecting endpoints from brute-force attacks and DDOS abuse. β (correct answer)
- C. It compresses the JSON payload.
- D. It restarts the server node process dynamically.
Explanation: rate-limit limits IP request counts, returning 429 Too Many Requests if limits are exceeded.
Question 30: How does res.sendFile() behave in Express?
- A. It uploads a file from the server to S3.
- B. It reads a file from absolute paths on the server and streams it to the client, setting correct content types automatically. β (correct answer)
- C. It deletes the target file after routing.
- D. It sends the directory structure as JSON.
Explanation: res.sendFile(path) is standard for serving single pages or download attachments from the backend.