Express JS Express Routing 2 — Questions and Answers
Question 1: Which Express method defines a route that handles HTTP GET requests?
- app.get() (Correct answer)
- app.fetch()
- app.read()
- app.retrieve()
Correct answer: app.get()
app.get() registers a handler for HTTP GET requests at the specified path.
Question 2: What is route chaining in Express?
- Using app.route() to chain multiple HTTP method handlers for one path (Correct answer)
- Connecting multiple apps together
- Linking routes across different files
- Using nested route parameters
Correct answer: Using app.route() to chain multiple HTTP method handlers for one path
app.route() returns a route instance that allows chaining handlers for GET, POST, PUT, etc. on the same path.
Question 3: In Express, what regular expression pattern matches routes like /ab?cd?
- The 'b' and 'd' characters are optional (Correct answer)
- The 'a' and 'c' characters are optional
- The entire path is optional
- The path requires exactly one of each character
Correct answer: The 'b' and 'd' characters are optional
In Express route patterns, '?' makes the preceding character optional, so /ab?cd matches /acd and /abcd.
Question 4: What happens when you pass a string pattern '/ab*cd' as an Express route path?
- It matches /abcd, /abXcd, /ab123cd, etc. (Correct answer)
- It only matches /abcd exactly
- It matches any path starting with /ab
- It throws a syntax error
Correct answer: It matches /abcd, /abXcd, /ab123cd, etc.
The '*' wildcard in an Express route pattern matches any sequence of characters.
Question 5: Which property of the request object contains the query string parameters parsed as an object?
- req.query (Correct answer)
- req.params
- req.search
- req.qs
Correct answer: req.query
req.query contains the parsed query string as a key-value object.
Question 6: How do you define a catch-all route that handles any path not matched by previous routes?
- app.use('*', handler) or app.get('*', handler) placed last (Correct answer)
- app.default(handler)
- app.fallback(handler)
- app.catch(handler)
Correct answer: app.use('*', handler) or app.get('*', handler) placed last
Placing a wildcard route or middleware at the end of all routes catches any unmatched requests.
Which Express method defines a route that handles HTTP GET requests?