Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to access the express 'app' object from inside a separate route file?

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?

like image 850
mikemaccana Avatar asked Feb 26 '15 17:02

mikemaccana


People also ask

Why Express app and server files kept separately?

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.

What is the use of route in Express?

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.

What is app route in Express?

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 )

How do you create routes in an Express application?

Create a new file called things. js and type the following in it. var express = require('express'); var router = express. Router(); router.


1 Answers

You can simply access app by req.app in your route handlers

like image 157
Safi Avatar answered Nov 15 '22 04:11

Safi