Express : router object and methods - javascript

I have
var router = express.Router();
router.get('/', function(req, res) {
//something
}
module.exports = router;
Is the router created, the get method executed and the router exported, or is it that the router is created, the method is define for this router (not executed) and the router is exported afterwards?

Second one. Router is created, method is defined and router is exported. That method will be executed when browser sends get request on '/' url, if you correctly require exported router.

Related

How to call my middleware for all apis i have automatically?

I created a service in express to send emails, now I'm implementing a middleware for jwt authentication, it is already working, now I would like this middleware to be called automatically for any api I have or the ones I will cre
I tried to do the following assignment on my root, checkToken is my function on middleware
const app = express();
app.use(checkToken, require('./middlewares'))
app.use(`${config.URL_BASE}/email`, require('./apis/email'))
.
.
.
currently to call the middleware i'm doing, its works very well
router.post('', middleware.checkToken, async function (req, res) {
const {
type: typeCode,
.
.
.
its works very well, but my other api dont call the middleware, i didn't want to explicitly call again
Other api
router.get('/health', async (req, res) => {
res.status(200).send({ message: 'Ready.' })
})
To have middleware called for all routes, just do an app.use(yourMiddleware) before any of the routes are defined.
To have middleware called for one set of routes, but not other routes, put all the routes you want the middleware to be called for on a particular router that has a path prefix that only matches a subset of your routes. Then execute the middleware on that router before any of its routes are defined.
Here's an example of the 2nd option:
const express = require('express');
const app = express();
// load and configure api router
app.use('/api', require('./apiRouter.js'));
app.listen(...);
Then, inside apiRouter.js:
const router = require('express').Router();
// middleware that is called for all api routes
router.use(myMiddleware);
// define api routes here
router.get('/list', ...)
module.exports = router;
router.use() mounts middleware for the routes served by the specific router.
router.use(checkToken)
router.get('/health', getHandler)
router.post('/', postHandler)
module.exports = router

Nodejs - load module once and use in many different files

My project directory looks something like this:
MyProject
-app.js
-routes
-routeone
-routetwo
Inside of my app.js file it looks like this:
var express = require('express');
var app = express();
var myModule= require('myModule');
app.use(myModule());
var routeone = require('./routes/routeone');
var routetwo = require('./routes/routetwo');
app.use('/routeone', routeone);
app.use('/routetwo', routetwo);
.
.
.
Each route file looks something like this:
var express = require('express');
var router = express.Router();
router.post('/', urlencodedParser, function(req, res, next) {
//Need to call myModule's createUser function. How do I call it here?
});
module.exports = router;
As you can see I have a dependency on the myModule module. I need to call a function in this module in every route.I may have many more routes in the future. I would like to avoid specifying this (calling require) in every single route file because in the future if I have hundreds of route and say the module now accepts options I would need to to every single file and since this manually. Is there a way to require it once (e.g in the app.js file) and then be able to use it everywhere?
You can write your route modules as such that during the time of creation(require call) they get their dependencies injected. I have added a sample below
route.js
module.exports = function(myModule, router, dep1, dep2){
router.post()
//use my module, dep1 and dep2
}
app.js
var mymodule = require('./myModule')
var dep1 = require('./dep1');
var dep2 = require('./dep2');
var router = express.Router();
var route = require('route')(mymodule, router, dep1, dep2);
Update - For returning router instance from route.js
route.js
module.exports = function(myModule, dep1, dep2){
router.post()
//other router invocations
return router
}
In app.js
var customRouter = require('route')(mymodule, router, dep1, dep2);
the customRouter will be an router instance since thats what is being returned by te invoked function in route.js

Run a function when an api route is mounted

I am using express router for my app. I need to run a function when a particular route is mounted. I have two files, index.route.js and currentUser.route.js
index.route.js
import currentUserRoutes from './currentUser.route';
const router = express.Router();
//mounts the '/me' route on currentUserRoutes
router.use('/me', currentUserRoutes);
export default router;
currentUser.route.js
const router = express.Router();
//line below throws an error
router.on('mount' , () => {console.log("me route mounted")});
router.route('/')
.get(currentUserCtrl.get)
export default router;
It throws an error saying router.on is not a function, I have tried placing the router.on part in index.route.js too, but there too I am getting the same error. Any help would be appreciated.
try this:
router.on('mount' , function(){console.log("me route mounted")});

Remove Router From Express.js Route Stack

I have an Express.js project where I am allowing plugins to be loaded and unloaded at runtime. Plugins have access to the Expess.js router stack to register their paths just like a normal script would such as:
var express = require('express');
var router = express.Router();
module.exports = function(projectCoreObject) {
function Plugin() { }
// Plugin initialize called when a plugin is loaded.
Plugin.Initialize = function (done) {
// Register the router..
projectCoreObject.app.use('/', router);
};
// GET - /test
router.get('/test', function(req, res, next) {
res.send('Success!');
});
return Plugin;
};
While this all works great, I have the issue with unloading plugins removing their router from the stack.
Is there a proper way to remove a full router object from Express.js' stack at runtime? I can do individual middleware using their names but with a route like this example shows, the name is just 'router' in the stack.
I resolved this by using a named function trick to take an anonymous function and turn it into a named one. This way I can remove the router by its name then.

Node.js router() usage confusion

why we need to use for example var route = Router(); since by default below simple example of express already fullful the usage of route :
var express = require('express'),
app = express();
app.get('/login',function(req,res,next){
//..something
});
The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.
Create a router file named birds.js in the app directory, with the following content:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
Then, load the router module in the app:
var birds = require('./birds');
...
app.use('/birds', birds);
The app will now be able to handle requests to /birds and /birds/about, along with calling the timeLog middleware specific to the route.

Categories