In Express 4, by default, routes are loaded from a separate file:
app.use('/', routes);
Would load routes/index.js
.
I have a third-party library that attaches to app
itself. Is there a preferred way to access app
from inside routes/index.js
?
I've thought about dependency injection ie, routes/index.js
does
module.exports = function(app){
(routes go here)
}
and then:
app.use('/', routes(app))
But I wonder if there's a better way. What's the best way to access the express 'app' object from inside a separate route file?
Applying a similar concept to the project structuring of Express, the separation of the application logic from the server allows the code to be modular and follow a MVC (Model-View-Controller) model. The separation is essential to reduce coupling and to encapsulate and abstract the inside logic of application.
A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern. There are several ways to create routes.
The app. route() function returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app. route() to avoid duplicate route names (and thus typo errors). Syntax: app.route( path )
Create a new file called things. js and type the following in it. var express = require('express'); var router = express. Router(); router.
You can simply access app by req.app in your route handlers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With