Express JS Express Routing 1 — Questions and Answers
Question 1: Which method defines a route that responds to all HTTP methods in Express?
- app.all() (Correct answer)
- app.any()
- app.every()
- app.universal()
Correct answer: app.all()
app.all() matches all HTTP methods for a given path.
Question 2: What is the correct way to define a route parameter named 'id' in Express?
- /user/:id (Correct answer)
- /user/{id}
- /user/[id]
- /user/$id
Correct answer: /user/:id
Express uses the colon syntax :paramName to define named route parameters.
Question 3: How do you access a route parameter named 'userId' in an Express handler?
- req.params.userId (Correct answer)
- req.query.userId
- req.body.userId
- req.id.userId
Correct answer: req.params.userId
Named route parameters are available on the req.params object.
Question 4: Which Express object is used to create a modular, mountable route handler?
- express.Router() (Correct answer)
- express.Route()
- express.Module()
- express.Handler()
Correct answer: express.Router()
express.Router() creates a mini-application capable of performing middleware and routing functions.
Question 5: How do you mount a router module at the path '/api' in Express?
- app.use('/api', router) (Correct answer)
- app.mount('/api', router)
- app.attach('/api', router)
- app.route('/api', router)
Correct answer: app.use('/api', router)
app.use() mounts middleware or a router at a specified path prefix.
Question 6: What does the next() function do inside an Express route handler?
- Passes control to the next matching middleware or route (Correct answer)
- Sends the response to the client
- Ends the request-response cycle
- Redirects to the next URL
Correct answer: Passes control to the next matching middleware or route
Calling next() passes control to the next middleware function in the stack.
Which method defines a route that responds to all HTTP methods in Express?