Express routes invoking multiple router function - node.js

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>

Related

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;

Difference Between app.use() and router.use() in Express

I was just reading the documentation on express and found these two terms, app.use(); and router.use();
I know app.use(); is used in node for Mounting a middleware at a path, and we often use it in most of the node apps. but what is router.use(); are they both same? if not, whats the difference ?
I read about router here. I also found similar questions on SO What is the difference between "express.Router" and routing using "app.get"?
and Difference between app.all('*') and app.use('/'), but they do not really answer my question. Thanks.
router.get is only for defining subpaths. Consider this example:
var router = express.Router();
app.use('/first', router); // Mount the router as middleware at path /first
router.get('/sud', smaller);
router.get('/user', bigger);
If you open /first/sud, then the smaller function will get called.
If you open /first/user, then the bigger function will get called.
In short, app.use('/first', router) mounts the middleware at path /first, then router.get sets the subpath accordingly.
But if we instead use the following:
app.use('/first', fun);
app.get('/sud', bigger);
app.get('/user', smaller);
If you open /first in your browser, fun will get called,
For /sud, bigger will get called
For /user, smaller will get called
But remember for /first/sud, no function will get called.
This link may also help: http://expressjs.com/api.html#router
router.use(); mounts middleware for the routes served by the specific router, app.use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.use('/ANYROUTESHERE', yourMiddleware());).
Example use case could be an app with one router with standard routes and one router that handles api routes, which need a valid user.
You would then mount the authentication middleware for the api router only with router.use(yourAuthMiddleware());.
If you would have an app though that requires a valid user for all routes, mount the middleware for the app with app.use(yourAuthMiddleware());
app.use() used to Mounts the middleware function or functions at the specified path,the middleware function is executed when the base of the requested path matches path.
router.use() is used to middleware function or functions, The defaults mount path to “/”.
But in
app.use() you will have to give a specified path like that:
var adsRouter = require('./adsRouter.js');
app.use('/ads', adsRouter);
or
app.use('/ads', function(req, res, next) {
// write your callback code here.
});
But while using router.use() you can give only middleware, like this:
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
or
router.use('/test', function(req, res, next) {
// write your callback code here.
next();
});
or
//in router.js
router.use('/admin', authUtil.verifySessionId, authUtil.verifyLisencee);
router.post('/admin', controllerIndex.ads.adListingAdmin);
In the above code when the end point is '/admin' then first it will call the authUtil.verifySessionId and authUtil.verifyLisencee then it will execute next line with 'admin' end point and according to controllerIndex.ads.adListingAdmin method.
app.use(middleware): application-level middleware.
router.use(middleware): router-level middleware.
("middleware" refers to methods/functions/operations that are called between processing the request and sending the response.)
See https://expressjs.com/en/guide/using-middleware.html for a comparison of different types of middleware used in an Express app.
When looking at the express js docs for Routing (https://expressjs.com/en/guide/routing.html#express-router):
Use the express.Router class 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”.
A Router created with express.Router() is no different than an app created with express() in terms of functionality; it's like a logical grouping of routes/handlers/services/databases/etc. The biggest difference is the scope that it affects. A router just affects its own scope while the app is like the master/global scope for your web/app server. You could have many routers or "apps" running on one main app/web server instance. This is why you could listen to requests on an app instance via app.listen(80) but not on a router.

Router in Node Express 4

This is a question on how router is handled underneath.
If I have router:
var router = express.Router();
router.get('/', function(req, res) {
res.end('router');
});
app.use('/', router);
If I've fetch anywhere other than http://localhost/, say http://localhost/whatever I'll get a Cannot GET whatever. Who is giving out this message? I think it's the router, is it correct?
Now if I add a middleware after the router.
app.use('/', function(req, res) {
console.log('-------> here');
});
Now if I go to http://localhost/whatever,then the browser never gets any response back and is just hanging there waiting for stuff.
So, it means the middleware architecture knows that if another middleware is added, then router does not have the final say. And it is expecting another route with possibly another router instance to be added. But if not, then router has the final say.
Isn't that kind of inconsistent? Somehow the router, which is itself a middleware, and the app object kind of know what each other is doing? Because router behave a little differently (call next() or give out "Cannot get" message) depending on whether another middleware is added.
I kind of dig into the code I can't really tell, but it looks like the entire middleware architecture is handled by the router object. Can someone explain a bit what's going on? Thanks.
You are missing one key step in your middleware. Middleware is a chain of asynchronous functions. Each one is called, in turn, with a reference to the next one. The expectation is that you pass control to the next middleware in the stack when you are done, which you are not doing.
app.use('/', function(req, res) {
console.log('-------> here');
});
Try this:
app.use('/', function(req, res, next) {
console.log('-------> here');
next();
});
What will happen then is control will get passed to the router just as it did without your middleware. The router cannot find any routes to handle /whatever, so you still get a 404 not found error.
I'm not sure that this is router who's giving "Cannot get" message.
Each middleware and the app itself try to handle the request in the order that they are being called.
If there is no router's or app's get (or post, etc.) able to handle the request, "Cannot get" message appears.
In the first scenario (before adding a middleware after the router), router can't handle the request, so Express looks forward
to find another app.use or app.METHOD, and not finding, it shows "Cannot get" message.
In the second scenario, another app.use after the router does exist, so it handles the request.
Thus, as for me everything is consistent.
Hope my answer helps you, but if your vision doesn't match mine, I'm ready for discussion :P
P.S. Sorry for my English

Express js why use a Router?

Why would I do:
var router = express.Router();
router.get('/', ...)
instead of
app.get('/', ...);
The two will give me the same result. What's the point of instantiating a router if app is already a router?
It's useful if you're writing a very complex app. For example, you might have a tree like this:
routes
user.js
post.js
server.js
In both user.js and post.js, you would create a Router object and export it. You can attach all the routes for the user to that router - say /user/new, /user/edit, and /user/1, and /post/new, /post/edit, and /post/1.
In server.js, you would require each of your routes and attach their routers via app.use:
app.use('/user', user);
app.use('/post', post);
All requests to /user will then be sent to the user router, and all requests to /post will be sent to the post router. Then, you can register routes like:
router.get('/new', function(req, res) { });
And it will automatically be mapped to /user/new or /post/new. This is useful because it helps organize your app, and it forces you to segregate one section of your application into one file (separation of concerns and all that). It's a useful part of express that isn't very well advertised.
Revisiting the router middleware
The router middleware is very special middleware. While other Express
middlewares are inherited from Connect, router is implemented by
Express itself. This middleware is solely responsible for empowering
Express with Sinatra-like routes.
The router middleware is a middleware system of its own. The route
definitions form the middlewares in this stack. Meaning, a matching
route can respond with an HTTP response and end the request flow, or
pass on the request to the next middleware in line.
and then
To ensure predictability and stability, we should explicitly add
router to the middleware stack
app.use(app.router);

How does mounting apps in Express work

So I've seen TJ's guide to creating modular Express-apps, followed it to good effects, but want to know more about the details of how it works, however a search gives me no answers.
In short I am wondering: When mounting apps in Express, what parts of the apps are shared and what parts are not?
Some examples to clarify my question:
app.js:
app.use(express.bodyParser());
app.use(loginApi); //loginApi is an express app
app.listen(3000);
This example works. But if I place the app.use(loginApi) before app.use(express.bodyParser()); , the body parser will not be available in the loginApi subapp. Why is that?
Another example:
submodule.js
var app = module.exports = require('express')();
app.all('*', function(req, res, next){
console.log('nifty middleware');
next();
});
app.js
app.get('/funtimes', fn);
app.use(submodule);
app.listen(3000);
Now in this example, If I understand it correctly, the /funtimes route will not be affected by the submodule middleware for all routes. But what about the rest of the routes of app.js ? Will they be affected? And what if I add another module, will it be affected?
if I place the app.use(loginApi) before app.use(express.bodyParser()); , the body parser will not be available in the loginApi subapp. Why is that?
That's because of the way Express handles requests. Any incoming request starts at the top of the middleware stack, starting with app.use() stack.
Middleware are simply functions that have the function signature function(req, res, next) which either call next() if they want to hand off the request to subsequent functions, or send a response themselves. You define a 'middleware chain' of a bunch of these functions (many are provided by express, like express.logger() and express.compress().)
So in the following scenario:
app.use(express.bodyParser());
var loginApi = require('./api/index.js')
app.use(loginApi);
app.use(app.router);
then an incoming request will first hit app.use(express.bodyParser()), parsing req.body. Then that function calls its internal next(), passing it to the next function in the middleware chain (app.use(loginApi)). The loginApi app has its own middleware chain, but the requests already have req.body set from the outer app. If the loginApi doesn't send a response, the request will continue to app.use(app.router) and at that point the requests will go to the routing functions you set up in your outer app.
So the answer is: A mounted app will have the middleware functions shared, which are placed before the line app.use(loginApi)
Middleware runs in order (until one of the middlewares doesn't call next()).
If you use() your mounted app before use()ing bodyParser, the entire sub-app will run before bodyParser adds its properties.
What you're asking about is middleware. This confused me for a while. Middleware are the functions that run in order to take a request in and serve back a response. app.use() takes a function as its only argument. That function manipulates the request in a consistent way.
app.use is a lot like app.all("*").
The order matters. For example, you might want to run a validator before serving the response.
One thing I learned recently is that you can pass an array of middleware functions to a route. For example
app.get("/whatever",[
function(req,res,next}{
...validation...
next();
},
function(req,res) {
...actions....
res.send(200);
}
]);
The next callback tells express to run the next function in the middleware. Middleware can also modify the request object. This is used a lot in authentication. For example, you'll see req.user getting defined from the database so in later middleware you'll be able to refer to properties of the user. But, it can also be used for a ton of other stuff.

Resources