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.
Related
Lets say I've some REST api server (maybe Express one).
When the life cycle begins (i.e someone GET 'http://foo/bar') there is some data in the Request object.
So let's say I've got something like this:
const method1 = require('some-module').method1;
app.get('/foo/bar', (req, res, next) => {
method1();
});
I want a simple way in the some-module.js to get a winston instance that somehow knows about all relevant data so I don't need every time to pass the request object all over my code.
The trivial solution is to pass the method1 the object and inside do like
method1(req){
winston.info('my message', {requestId: req.id};
}
But this is ugly because I need to change the signature of all my stuff just for logs.
Another option is to make everything a class that extends winston and do something like
app.get('/foo/bar', (req, res, next) => {
const foo = new Foo(new winstonWrapper(req));
});
and than foo.info('msg') will call something like winston.info('msg',{reqId:req.id})
What an elegant way can you suggest to create a winston instance upon request and use it in other modules easily?
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)
I have two routes added in this order:
/:foo
/login
The way how my app is structured is that the routes may be added dynamically. So, I do want to catch any site page (e.g. /hello-world, matched by :foo), but I do want that the specific route /login to have higher priority than the other one.
I know that the middleware get executed in sequential order, so, ideally I have to change the order of the calls, but since this is happening dynamically, is there a better way to do it?
How can I tell Express that the routes without dynamic stuff in them (pretty much containing :) should have priority over the ones that are dynamic?
You should place a route with the higher priority early than other.
app.get('/login', (req, res) => {
res.send('login');
});
app.get('/:foo', (req, res) => {
res.send('fooooo');
});
Then it will work
I don't think it's possible with "plain" Express, but this may work:
let Router = express.Router;
let MyRouter = function() {
let instance = Router.apply(this, arguments);
let handle = instance.handle.bind(instance);
instance.handle = function(req, res, out) {
this.stack.sort((layer1, layer2) => {
let path1 = layer1.route.path.replace(/:[A-Za-z0-9_]+/g, ':');
let path2 = layer2.route.path.replace(/:[A-Za-z0-9_]+/g, ':');
return path1.length < path2.length;
});
return handle(req, res, out);
};
return instance;
}
express.Router = MyRouter;
It basically monkeypatches the handle method of express.Router to sort the layer stack (which contains the routes) prior to handling the request. It sorts routes based on the length of the path (longer paths take priority), and hardcodes parameters in paths to have a length of 1 (so /:foo has a length of 2, and / has a length of 1; if you have paths like /x, you may have to fix this).
Very much untested, but at least it may provide an idea on how to tackle this.
I'm writing some rest API with Node.JS and Express. So for each API, I'd need to do all the usual stuff like parameter validation, authentication, authorization and then the actual business logic. Some sodo code to illustrate this:
router.get('/users', function (req, res){
async.auto(
authenticateCaller();
authorizeCaller();
validateParams();
doGetUsers();
)
})
This style certainly works but it makes the whole function very cumbersome by including a lot of extra pre-purpose codes. I know in web app programming, MVC has been introduced to separate UI, Module and Controller into different code groups, which is much cleaner. Is there any similar framework that can be helped to achieve this purpose?
Use middleware. Middleware is just a function that takes in three parameters:
function (req, res, next) {}
Call router.use() to register middleware before defining any routes. This will cause that middleware to be called before every route is executed.
These are all functions of middleware:
authenticateCaller();
authorizeCaller();
validateParams();
http://expressjs.com/en/guide/using-middleware.html
This is what I do.
Using Routes for Node.js Here I am making way for a folder named routes that has all the codes in it.
var routes = require('./routes');
var route_add_user = require('./routes/add_user');
Calling the function with the route here; .adduser is function name within that js file
app.get('/adduser', route_add_user.adduser);
define a function do your routine jobs
fuction auth(res,req,next){
authenticateCaller();
req.isAuthorized = authorizeCaller();
validateParams();
next();
}
router.get('/users',auth);
router.get('/users', function (req, res){
if( req.isAuthorized)
{..do some stuff here..}
})
This is one of the STYLE i was following to authenticate and use the API in express framework.
register.js
-----------
exports.addUser = function(req, res) {
// do something
};
exports.deleteUser = function(req, res) {
// do something
};
routes.js
---------
var register = require('./register');
router.get(‘/register’,auth, register.addUser);
router.get(‘/deleteUser’,auth, register.deleteUser);
// Better make it separate common file to reuse all the API
function auth(req,res,next) {
// do something to authenticate your API
}
It seems that if I want to move to a "next" function in Nodejs (and possibly Javascript in general?) I cannot pass parameters to the next function.
Here is what I mean:
app.get('/webpage', SomeFunction, NextFunction);
function SomeFunction (req, res, next) {
// Do things
next();
}
function NextFunction (req, res) {
// Do other things
}
Now, if in SomeFunction I were to say next(req, res); it does not seem to work. It never gets to the method. Obviously I cannot directly pass parameters...but my question is why? How does the next function know which parameters to use? Is it because they are named the same or does it automatically pass the 1st and 2nd parameters? If NextFunction used blah, bleet instead of req, res would it still work?
This is an intentional aspect of the design of Connect (the node.js middleware that's responsible for this behaviour). The next function your middleware receives is not the next middleware in the stack; it's a function that Connect generates which asks the next middleware to handle it (as well as doing some extra stuff to handle special cases, like when there isn't a "next middleware").
If your middleware should return a response, just do so. If it shouldn't, it's implied that some later middleware should return a response. If you need to pass along data to that later part of the process, you should attach it to an appropriate part of the request object req.
For example, the bundled bodyParser middleware is responsible for populating req.rawBody and req.body based on the contents of the request body. The bundled basicAuth middleware populates req.remoteUser based on the HTTP authentication.
This is the pattern you should try to emulate: a stack of middleware, each of which does a basic incremental thing to process the request. If what you're trying to model doesn't fit into this paradigm, then you should probably just have a single function to handle the request, from which you can call all of your own application logic however you like.