Express, multiple routes to same function - node.js

I am mimicking another api. I would also like to provide a different (better IMHO) api as well.
// this is url I need to support
api.post('/books/updateBook', function(req, res) {
...
});
// Would also like to support
api.put('/books/:bookId', function(req, res) {
...
});
I could easily do:
var updateBook = function(req, res) {
...
}
// this is url I need to support
api.post('/books/updateBook', updateBook);
// Would also like to support
api.put('/books/:bookId', updateBook);
Perfectly acceptable right? Being new to express I am wondering if there is a more 'express' way to handle this. I know you can use regex, but I am not sure you can map regex across different HTTP verbs (POST vs PUT).
Thoughts?

api.all('/books/:bookId', function (req, res, next) {
if (req.method === 'PUT' || req.method === 'POST) {
//get your groove on
} else {
next();
}
});
You can combine verbs in express, you just use all and examine the method, if it matches, handle the request other wise pass it down the handler chain (with next();).
That being said I think you're doing it right, there's no reason route handlers need to be lamdas.

Related

Nodejs Express router middleware for all methods except get

Is there a way to exclude a specific method (say GET) when creating a middleware for route methods that share part of the path?
For example, I have a lot of routes of the form /api/item/*. I want to have something like this to check for bad data
router.all('/api/item/*', (req, res, next) => {
const { itemId } = req.body;
if (!itemId) return res.sendStatus(404);
/* rest of logic here */
next()
});
But obviously I don't want GET to also go through this logic as it will have no req.body.
Any thoughts?
As posted in comments above one solution is if (req.method === 'GET') return next();
Another I thought of shortly after (though, not as elegant) is to order my route declarations as such:
router.get(...);
router.all(...);
Thus only applying the data-checking logic to non-GET requests.

using middlewares for specific namespaces in restify

I would like to use a middleware for checking users credentials only for some routes (those that start with /user/), but to my surprise server.use does not take a route as first argument and with restify-namespace server.use effect is still global.
Is there other way better than passing my auth middleware to all routes alongside the controller?
I think I'm going to just use server.use and inside the middleware make the following route check:
if (req.url.indexOf('/user/') !== 0) {
return next();
}
Unfortunately restify doesn't seem to be like express, which support the * operator. Hence, What I would suggest is grouping the routes that you desire together and apply a .use before them.
That is:
server.get('/test', function(req, res, next) {
// no magic here. server.use hasn't been called yet.
});
server.use(function(req, res, next) {
// do your magic here
if(some condition) {
// magic worked!
next(); // call to move on to the next middleware.
} else {
// crap magic failed return error perhaps?
next(new Error('some error')); // to let the error handler handle it.
}
});
server.get('/admin/', function(req, res, next) {
// magic has to be performed prior to getting here!
});
server.get('/admin/users', function(req, res, next) {
// magic has to be performed prior to getting here!
});
However, I would personally advocate the use of express, but choose whatever fits your need.

Dynamic post/put routing in ExpressJS

I'm using Angular on the client side, Express on the server. I've got two forms on the same page. I need both forms to post to the same URL, but use a different controller method, depending on a variable that I can grab from the request body.
Obviously the routes listed below would work individually, but since I need both, having two PUTs on the same URL won't work:
app.put('/articles/:articleId', articles.update);
app.put('/articles/:articleId', articles.addEditor);
In pseudo-express code, what I'd like is:
app.put('/article/:articleId', function(req) {
if (req.editor) {
articles.addEditor;
} else {
articles.update;
});
How about:
app.put('/article/:articleId', function(req, res, next) {
if (req.body.editor) {
articles.addEditor(req, res, next);
} else {
articles.update(req, res, next);
}
});

Proper way to remove middleware from the Express stack?

Is there a canonical way to remove middleware added with app.use from the stack? It seems that it should be possible to just modify the app.stack array directly, but I am wondering if there is a documented method I should be considering first.
use actually comes from Connect (not Express), and all it really does is push the middleware function onto the app's stack.
So you should be just fine splicing the function out of the array.
However, keep in mind there is no documentation around app.stack nor is there a function to remove middleware. You run the risk of a future version of Connect making changes incompatible with your code.
This is a useful functionality if you are inheriting some unwanted middleware from a framework built on express.
Building on some of the answers that came before me: In express 4.x the middleware can be found in app._router.stack. Note that the middleware are invoked in order.
// app is your express service
console.log(app._router.stack)
// [Layer, Layer, Layer, ...]
Tip: You can search the individual layers for the one you want to remove/move
const middlewareIndex = app._router.stack.findIndex(layer => {
// logic to id the specific middleware
});
Then you can just move/remove them with standard array methods like splice/unshift/etc
// Remove the matched middleware
app._router.stack.splice(middlewareIndex, 1);
There seems to be no built in way to do that, but you can manage to get the same result with a small trick. Create your own array of middleware (let's call it dynamicMiddleware) but don't push that into express, instead push just 1 middleware that will execute all the handlers in dynamicMiddleware asynchronously and in order.
const async = require('async')
// Middleware
const m1 = (req, res, next) => {
// do something here
next();
}
const m2 = (req, res, next) => {
// do something here
next();
}
const m3 = (req, res, next) => {
// do something here
next();
}
let dynamicMiddleware = [m1, m2, m3]
app.use((req, res, next) => {
// execute async handlers one by one
async.eachSeries(
// array to iterate over
dynamicMiddleware,
// iteration function
(handler, callback) => {
// call handler with req, res, and callback as next
handler(req, res, callback)
},
// final callback
(err) => {
if( err ) {
// handle error as needed
} else {
// call next middleware
next()
}
}
);
})
The code is a bit rough as I don't have a chance to test it right now, but the idea should be clear: wrap all dynamic handlers array in 1 middleware, that will loop through the array. And as you add or remove handlers to the array, only the ones left in the array will be called.
You can use the express-dynamic-middleware to make this.
https://github.com/lanbomo/express-dynamic-middleware
Use it like this
const express = require('express');
// import express-dynamic-middleware
const dynamicMiddleware = require('express-dynamic-middleware');
// create auth middleware
const auth = function(req, res, next) {
if (req.get('Authorization') === 'Basic') {
next();
} else {
res.status(401).end('Unauthorization');
}
};
// create dynamic middleware
const dynamic = dynamicMiddleware.create(auth);
// create express app
const app = express();
// use the dynamic middleware
app.use(dynamic.handle());
// unuse auth middleware
dynamic.unuse(auth);
No way of removing a middleware as far as I know. however, you can assign a boolean flag to 'deactivate' a middleware at anytime you want.
let middlewareA_isActivate = true;
// Your middleware code
function(req, res, next) {
if (!middlewareA_isActivate) next();
// .........
}
// Deactivate middleware
middlewareA_isActivate = false;
EDIT :
After reading through ExpressJs (4.x) code, I notice that you can access the middlewares stack via app._router.stack, manipulation goes from there I guess. Still, I think this 'trick' might not be able to work in future Express
P/s: Not tested how Express behaves when manipulate the middlewares stack directly though
Following from the hints above, I've add success with the following on express 4.x. My use case was logging what was coming in with Slack Bolt, so I could capture and then mock it:
// Define a handy function for re-ordering arrays
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
// Use the normal use mechanism, so that 'extra' stuff can be done
// For example, to log further up the order, use app.use(morgan("combined"))
app.use([my-middleware]);
// Now adjust the position of what I just added forward
const numElements = app._router.stack.length;
app._router.stack.move(numElements - 1, 1);
You can use
console.log("Stack after adjustment", app._router.stack)
to confirm the new order is what you want. (For Slack Bolt, I had to use app.receiver.app because the Bolt app wraps the express app.)
We can write like this.
// route outside middleware
route.get("/list", (req, res)=>{
res.send("from listing route");
});
//use middleware
router.use(Middlewares.AuthMiddleware.isValidToken);
//routes inside the middleware
route.post("/create", (req, res)=>{
res.send("from create route");
});
route.delete("/delete", (req, res)=>{
res.send("from delete route");
});
So basically, write routes before injecting middleware into your route.

nodeJS route all request

I am writing a nodejs application.
I want to to route all the requests to some common API. For that I am using
app.get('*', function(req, res) {
/* Do Something */
});
In "Do Something" Section I want to retrive the req.route.regexp and then based on that I will do processing. I am expecting req.route.regexp should be the exact URL's regexp for which we came here. But as I am handling this in '*', so regular expression is not giving me equivalent req.route.params.
So is there any way to get the regexp based on req.route.params in app.get of all routes (*).
Ex: I have url as: "/:val", for that I am expecting regexp
"/^/(?:([^/]+?))/?$/i", but I am getting regexp for "*",
so how I can achieve this?
When the handler of app.get('*', ...) is called, the eventual route hasn't been matched yet and express cannot possibly tell you about a subsequent route.
The only solution that I see would be to manually call a handler in all your routes:
app.get('/:val', function (req, res) {
if(!myGlobalHandler(req, res))
return;
});
function myGlobalHandler(req, res) {
if(somethingWrong(req)) {
res.send({error: 'uh oh...'});
return false;
}
return true;
}
If you tell me more about your use-case, maybe there's a more elegant solution.

Resources