GET routers does not called our express.js - javascript

If you have placeholders and predefined routes at the same place, the predefined ones never get called, if the placeholder was declared before the predefined ones.
Example:
router.get("/:id", fetchEntry)
router.get("/fancy-action/", doSomethingFancy)
<-- if ordered in that way, fancy-action would call fetchEntry instead of doSomethingFanc

Put the most specific routes fancy-action before the general one :id:
router.get("/fancy-action/", doSomethingFancy)
router.get("/:id", fetchEntry)

Define /fancy-action route before the /:id
router.get("/fancy-action/", doSomethingFancy)
router.get("/:id", fetchEntry)

Related

How to use exact match in ExpressJs router

I have two routes as follow in my ExpressJs application
router.get("/task/", Controller.retrieveAll);
router.get("/task/seed/", Controller.seed);
If I make a request on /task/seed/ instead of Controller.seed, Controller.retrieveAll is getting called.
So basically router matches the /task/ string before it checks the proceeding string, in my case /seed.
How can I make sure that the router does check the full string (kind of exact match)?
The example you show using router.get() or app.get() does not actually occur. router.get() does not do partial matches unless you're using wildcards or regexes.
I verified that in this simple test app:
const express = require('express');
const app = express();
app.get("/task/", (req, res) => {
res.send("got /task");
});
app.get("/task/seed", (req, res) => {
res.send("got /task/seed");
});
app.listen(80);
When you request /task/seed, you get the message got /task/seed so, it does route correctly.
On the other hand, router.use() does do partial matches so this problem could occur if your actual code was using .use(), not .get(). In that case, you just need to either switch to the verb-specific .get() instead of using the generic .use() or you need to order your routes from the most specific to the least-specific so that the most-specific declaration gets a chance to match first:
router.use("/task/seed/", Controller.seed);
router.use("/task/", Controller.retrieveAll);
In case you're curious, the two main differences between router.use() and router.get() are:
.get() only matches GET requests while .use() matches all HTTP verbs.
.get() only does full path matches while .use() will match any URL path that starts with what you specify.
Execution of express router middleware functions is sequential. There is no keyword like exact, as we have in react-router to make the router check for exact path match.
To make your code work, and always when creating express routes, have the path with the higher specificity above the path with lesser specificity.
So, this should work:
router.get("/task/seed/", Controller.seed);
router.get("/task/", Controller.retrieveAll);
These earlier StackOverflow answers will be very helpful:
https://stackoverflow.com/a/32604002/6772055
https://stackoverflow.com/a/27317835/6772055

Passing Node.js middleware to a custom function

Question about express middleware. Say I have a route like the following:
router.route('/replies/:board')
.post(bodyThreadIdVal, textVal, passVal, replyHandler.postReply)
Now let's say I wanted to move the first three middleware arguments from above out of the post method and into a custom method I created in another file, named postReply. How would I go about doing this? I thought maybe using app.use within my postReply method but not sure exactly how or if there is a cleaner way.
I have tried a few methods including
this.postReply = async (req, res, next) => {
app.use(bodyThreadIdVal, textVal, passVal)(req, res, next)
/* additional code */
}
But this seems to cause a recursive loop that rejects with Maximum call stack size exceeded
If the only reason of moving middlewares into a sepparate file is groupping them in one place and making code cleaner and there is no necessity to create a function that will combine your middlewares then I would suggest to group such connected middlewares into an array:
const postReply = [bodyThreadIdVal, textVal, passVal];
router.route('/replies/:board')
.post(...postReply, replyHandler.postReply);
If you will need to add some /* additional code */ just create a new middleware and add it to postReply array. This is definitely much cleaner way.

Node.js:Route precedence and ordering (sails.js)

In my sails.js application i have two routes like this:
'/': {controller:'HomeController',action:'home'},
'GET /:category/:subcategory/:keyword':{controller:'SearchController',action:'index'
When I run the default route (/) it will always execute this route
GET /:category/:subcategory/:keyword .
Why is this happening??
The order of routes in route file is
1) /
2) GET /:category/:subcategory/:keyword
As mentioned in the comment above, your very general route /:category/:subcategory/:keyword is being hit because it must match asset urls on your homepage. This route will match any three-part path, ex:
/images/icons/smiley.png
/scripts/thirdparty/jquery.min.js
Etc!
There would be two approaches to fix this. One would be making your SearchController urls more specific. Maybe /search/:category/:subcategory/:keyword would be a good idea? This is the simplest and should clear up any conflicts with your assets right away.
But if you really need catch-all routes that can interfere with other specific routes, then the solution is to catch the specific routes first. For example, in routes.js:
'GET /images/*': 'RouteController.showAsset',
'GET /scripts/*': 'RouteController.showAsset',
'GET /styles/*': 'RouteController.showAsset',
//...
'GET /:category/:subcategory/:keyword': 'SearchController.index',
Then create a controller RouteController with the method:
showAsset: function(req, res) {
var pathToAsset = require('path').resolve('.tmp/public', req.path);
// ex should be '.tmp/public/images/icons/smiley.png'
return res.sendfile(pathToAsset);
},
You may need to add something in to check for file existence first, but this is the idea.
I found this approach worthwhile when I wanted a /:userName route that would not conflict with all of my /contact, /about, /robots.txt, /favicon.ico, etc. However, it takes work to maintain, so if you think the first approach can work for you, I would use that.

Node Express - Route path colon parameter exception

Currently I have two routes in my app:
/invoice/:invoice returns JSON data of an Invoice document from Mongoose
/invoice/preview returns a preview of an invoice inside an HTML template (note that this doesn't always preview an existing invoice, it could also be a non-existing of which its data is supplied via url parameters, which is why the route cannot be /invoice/:invoice/preview)
Question
There should be a better way to declare these two specific routes, because the /invoice/preview route now calls both handlers, since it matches both regexes.
If we were talking in CSS selectors /invoice/:invoice:not(preview) would be the behavior I want. Unfortunately I don't find any documentation for this.
Is there any way to achieve this or any way to improve this endpoint structure?
Declare more specific routes first:
router.get('/invoice/preview', ...);
router.get('/invoice/:invoice', ...);
Express checks routes in order of declaration, so once it has matched a request against /invoice/preview (and provided that its handler sends back a response), the less-specific /invoice/:invoice won't be considered.
Alternatively, if :invoice should always match a specific pattern (say a MongoDB ObjectId), you can limit the route to requests matching that pattern:
router.get('/invoice/:invoice([a-fA-F0-9]{24})', ...);
That pattern doesn't match "preview", so the order wouldn't matter so much in that case.
If this isn't possible, you could create a middleware that would check if req.params.invoice matches "preview" and, if so, would pass along the request further down the handler chain:
let notIfPreview = (req, res, next) => {
if (req.params.invoice === 'preview') return next('route');
next();
};
router.get('/invoice/:invoice', notIfPreview, ...);
router.get('/invoice/preview', ...);
(documented here)

Get express original url input instead of the regexp

While using Expressjs, I can define middleware for routes, like this app.get('/home', fn);, but it's also possible to do the following:
const customRouter = express.Router();
customerRouter.get('/foo', fn);
customerRouter.get('/foo/:id', fn);
app.use('/custom', customRouter);
For the /home route, I can access app._router.stack, iterate through it and I can find the routes I declared by accessing an object on the stack and access the property route.
For customRouter, it almost works the same, I can access the route property, but it only gives me /foo and /foo/:id
Does anyone know how I can get the full url for it?
So a console.log would return /custom/foo or /custom/foo/:id

Categories

Resources