Regarding not able to get all the registered routes in node - node.js

I have used express router for us routing in my app
now i want to get list of all the registered routes but not able to get it
I have used route as follows
global.router = express.Router();
app.use('/api', require('./routes'));
I have declared all routes in routes.js file and that is working perfectly fine
but when I try to access the all the routes then it is return undefined in route
let allRoutes = app._router.stack.map(r => r.route.path)

app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route, r.route.path)
}
})
Can you make sure by consoling if you're getting list of all routes in app._router.stack?
If yes, then you can map through it by using forEach.
Make sure you have express version 4.x

Related

Express routes invoking multiple router function

I've created a NodeJS Express app. But my express route is invocking multiple routes function, one after another, but I only need one at a time.
My express app.js
app.use(routes)
Express router:
const router = express.Router();
router.post("/product", controller.productFunction)
router.post("/user", controller.userFunction)
router.get("/:id", idController.getId)
Whenever I create a post request for "/product" route, first the productFunction is invocked, but then the "/:id" routes getId function is also get invocked. Same thing happen for /user route as well. Always /:id route is getting invocked.
Is there any way to prevent this?
I even tried this way, but after the homepage loading then again it invockes getId function.
app.get("/", (req, res, next) => {
res.sendFile(..........);
});
app.use(routes);
I am sure that this is not an issue with the router itself.
You can't skip from POST to GET handling. So invocations are caused by different requests.
router.get("/:id", idController.getId) kind of wild card, and <server_url>/favicon.ico will trigger it
If you check it via browser it tries to get favicon or smth else and invokes this handler.
Try to make POST request via curl/Postman and idController.getId should not be called.
It is risky to serve static and process requests on a same level.
You can add some prefix to all your request, like that app.use('/api', routes); then static file will be available on /<file_name> and all server logic will be under /api/<request>

Problem using Nodejs / Express routing paths

I am a long time programmer but I'm new to Node and have a simple question about routing paths in Express which I cannot get to the bottom of.
I've developed a very simple app using node/express and MySql. I have then split up my GET and POST routes in the app just for convenience. I am using the route '/posts' at the app level and the sub route '/submit-form' in my router() which is the URL my form submits to.
I'm obviously doing something stupid because it doesn't work, I get the cannot POST message. If I use the full URL in the app and in the router then it works fine so there's nothing wrong with the code I think, only with my understanding of how express does routing.
Any advice appreciated.
A router should be used with the .use() method. Therefore, you should use the following in your app.js file
app.use('/posts', PostRoute)
When the nested router (on /posts) will handle the request, it will now based on the nested route declaration which HTTP method should match
app.js
const app = express();
app.use('/user', require('./routes/user'))
then inside the user;
const router = express.Router({});
router.post('/login', (req,res,next) => {
});
module.exports = router;

Routing in Express and MEAN stack

I am following an on-line tutorial of implementing in MEAN. Everything looks great. Except when it comes to routes. I understand that routes need to be in a javascript files (js extension). It's okay with a small web site. But as the number of requests grow, I would like to put them in separate files. I looked up in SOF for how to include files in Javascript. It is non-trivial. Has anyone faced this issue before? Can anyone comment?
Thanks
You can use Router Middleware by using express.Router(). This allows you to break your routes into different files. On a side note, middleware is very powerful and is worth learning about, its a huge part of Express.
Say you have an app that has a /users section. You can create a separate routes file called users.js that contains all routes that pertain to your /users resources. Then inside your server.js where your main Express app is listening, you can assign the users.js routes to the /users resource using app.use().
You can have as many routers as you'd like, all routes are read top-down when Express is deciding which route to use.
./routes/users.js
// Create an express router
var router = require('express').Router();
// Define a route for GET /
router.get('/', function(req, res) {
res.status(200).send('Welcome to /users');
});
// make our router available for require() statements
module.exports = router;
server.js
var express = require('express');
var app = express();
// Users routes
var users = require('./routes/users');
// Tell our app to use the Users routes defined in ./routes/users.js
app.use('/users', users);
app.listen(process.env.PORT || 3000, function() {
console.log('listening');
});

app router in Express

There currently is a difference between
app.use(function(req,res,next){
});
and
router.use('/some_route', function(req,res,next){
});
...The difference being that app.use runs for every request and router.use only runs for matching routes.
My question is about the router that must lie underneath app. Surely app has some default router internal to it. Is there a way to access that router...app.router? I thought that was deprecated?
Secondly, what I am really looking for is a way to access the current router being used.
For example,
app.use(function(req,res,next){
var currentRouter = req.app._router // (?)
});
or
router.use(function(req,res,next){
var currentRouter = req._router //(?)
});
where req._router would be equal to the same router for the router.use call of course.
In the latest Express code, the default app router is in app._router.
It is created lazily which means it's not created until a route is actually defined (with app.use() or app.get() or something like that).
It does not appear that this is meant to be a public property and thus is subject to change. You can, of course, just define your own router with the root path and only use your own router and then you would not have to access or use this non-public property.
You are correct that app.router is deprecated. Trying to access it purposely throws an exception in the Express code.

Create ExpressJS Route Without Registering The Routing Module

In ExpressJS, you register the routing module like this:
app.use(app.router);
And you create a route like this:
app.get('/user/:id', function(req, res){
...
});
The problem is, if you create a route before you register the routing module then it is registered for you immediately.
For me, this is a problem because I'm building an NPM module that creates a route for itself. Right now, it has the unfortunate side-effect of registering the routing module without the user's knowledge. So if they happen to require my module before they register the static file handler, then it wrecks everything.
So my question is, how can I register a route without automatically registering the routing module?
I imagine your module requires the user to pass in their app, kind of like this:
module.exports = function(userApp) {
userApp.get(...);
...
}
Instead, make a new Express app and export that:
var express = require('express'),
app = express();
app.get(...);
...
module.exports = app;
And instead of having the user pass their app to you, have them use the app you export:
var express = require('express'),
yourModule = require('your-module'),
userApp = express();
userApp.use(express.static(...));
userApp.use(yourModule);

Resources