Express all issue - express

I docs it said that this two way of defining two sequential midlewares are equivalent
http://expressjs.com/4x/api.html#app.all
app.all('*', requireAuthentication, loadUser);
Or the equivalent:
app.all('*', requireAuthentication)
app.all('*', loadUser);
But it if we have middlewares defined as:
var requireAuthentication = function(req, res, next){
req.params.someParam = 1
next()
}
var loadUser = function(req, res, next){
console.log('someParam', req.params.someParam)
...
}
In first case req.params.someParam inside loadUser will be 1, and in second case it will be undefined.
Is it a bug or wat?

In short: req.params doesn't persist across routes. Use res.locals instead.
Not a bug in Express, but not very intuitive. This is a good question!
req.params is for grabbing parameters out of a URL. For example, if you had a route defined like this...
app.get('/user/:id', function(req, res) {
res.send('user id == ' + req.params.id);
});
...and you visited /user/123, then req.params.id would be "123".
This params property is different for every route. Take a look at this example:
app.get('/user/:userid', function(req, res, next) {
// req.params.userid is defined in here
// req.params.id is NOT defined here
next();
});
app.get('/user/:id', function(req, res) {
// req.params.id is defined in here
// req.params.userid is NOT defined here
});
req.params isn't the same for every route, which explains what you're seeing.
Your first example has one route with two request handler functions, so they all have access to the same req.params object. Your second example has two routes with two request handler functions, so they're accessing different req.params objects.
If you're trying to persist data between different request handler functions across the same request, you should use res.locals. To rewrite your example:
var requireAuthentication = function(req, res, next){
res.locals.someParam = 1
next()
}
var loadUser = function(req, res, next){
console.log('someParam', res.locals.someParam)
...
}
Using res.locals will work whether you have one line or two.
Hope that helps!

Related

app.get with multiple arguments - e.g. app.get('/', requireAuth, (req, res) => { })

I am wondering how express.js works when you specify multiple argument in the app.get, for example:
app.get('/', requireAuth, (req, res) => { })
Here, I believe you have the slash "/" as the route, and (req, res) as arguments for the callback function. But there is also the 'requireAuth' part which was used for authorization. But in the documentation I don't find anything about multiple arguments in the way we use 'requireAuth' now. It does mention that you can use an array of functions but that is not used here (https://expressjs.com/en/guide/routing.html). How does it work?
P.S. The 'requireAuth' code for reference:
module.exports = (req, res, next) => {
const { authorization } = req.headers;
// authorization === 'Bearer laksjdflaksdjasdfklj'
if (!authorization) {
return res.status(401).send({ error: 'You must be logged in.' });
}
const token = authorization.replace('Bearer ', '');
jwt.verify(token, 'MY_SECRET_KEY', async (err, payload) => {
if (err) {
return res.status(401).send({ error: 'You must be logged in.' });
}
const { userId } = payload;
const user = await User.findById(userId);
req.user = user;
next();
});
};
All the arguments are simply middle-ware functions that you call before the actual route logic is run(for individual routes). As long as there is next handling in each of the middle-ware functions, the chain will run till your route logic, and then exit where next isn't handled.
This is the magic of express. You can do many things with it, like error handling, handling different content types etc.

How to isolate or fix no-response (browser hang) after calling passport.authenticate as middleware

I'm trying to use passport.authenticate('local') as middleware with passport-local-mongoose but it doesn't seem to pass control to the subsequent middlewares in my route.
I'm assuming there's an error but the following (err, req, res, next) middleware isn't being called so I'm wondering if I've misunderstood something basic about passport-local in general.
I've spent a few hours trying various things, searching here but I can't find a way to isolate my problem any further or get a better log of where control is going wrong in my route.
I've posted a small reproducible example to GitHub.
This is how I'm setting up BEFORE my routes:
// Get connected
mongoose.connect('mongodb://localhost/pass');
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => { console.error(err.message) });
// Basic user schema using nickname field as username
const Schema = mongoose.Schema;
const userSchema = new Schema({});
userSchema.plugin(passportLocalMongoose, { usernameField: 'nickname' });
const User = mongoose.model('User', userSchema);
// Initialise passport before routes
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
app.use(passport.initialize());
And this is the route with my passport.authenticate:
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
passport.authenticate('local'),
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
There are other routes with the pug views and registration.
Registration works fine, in mongo db.users.find() show a good looking entry for the new user.
But my /login post route doesn't get beyond passport.authenticate.
The console.log gets triggered, so I know the route is being called.
Based on my limited knowledge of express and passport, I'm expecting one of those two following middlewares to be triggered, one on success and one if it fails.
Neither is triggering.
Best way to isolate is covered in the authenticate docs under "Custom Callback", I just didn't understand it originally.
NOTE: I've saved the following in the answer branch on my repo, as posted in the question.
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
(req, res, next) => {
console.log('authenticating...')
passport.authenticate('local', (err, user, info) => {
console.log(req, res, err, user, info);
next(err);
}) (req, res, next);
},
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
What I realised
passport doesn't consider authentication FAIL as an err
it just leaves user null
basically you need to give it success and failure redirects if you want to use middleware form, don't do what I did and try to handle err etc.

How does the return of control flow work in a chain of Express middleware functions?

I actually have a couple of questions about Express middleware chaining and thought I'd group them in this single post since they're closely related.
Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get executed?
router.get('/a', (req, res, next) => {
res.sendStatus(200);
// Does this ever get executed?
});
router.get('/b', (req, res, next) => {
next();
// Does this ever get executed?
});
router.get('/c', (req, res, next) => {
return;
// Does this stop the middleware chain? What happens to the request/response?
});
Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an argument to create a certain middleware, and that argument is dependent on which Express app object is the owner of the Request. So I need to access a property of the Request before it is passed to the middleware that needs to be created using that property. Would this work: ?
router.get('/d', (req, res, next) => {
var middlewareFunction = createDynamicMiddleware();
middlewareFunction(req, res, next); // Will this still work as expected?
});
Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?
Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get
executed?
router.get('/a', (req, res, next) => {
res.sendStatus(200);
// Does this ever get executed?
// Yes, but don't call next() or res.send() or it will throw an error
});
router.get('/b', (req, res, next) => {
next();
// Does this ever get executed?
// Yes, but don't call next() or res.send() or it will throw an error
});
router.get('/c', (req, res, next) => {
return;
// Does this stop the middleware chain? What happens to the request/response?
// The request get stuck and after a while it will fail due 'timeout'
});
Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an
argument to create a certain middleware, and that argument is
dependent on which Express app object is the owner of the Request. So
I need to access a property of the Request before it is passed to the
middleware that needs to be created using that property.
Your factory of dynamic middleware should return a new function
Functions that returns new functions, are also knows as curried functions, here is a practical example:
// based on 'someId' we will return a specific middleware
req.get('/user/:someId',
createDynamicMiddleware,
(req,res) => {
res.send('ok')
})
function createDynamicMiddleware(req,res,next){
if(req.params.someId === 'me') {
return function(req, res, next){
// do some stuff if someId is me
return next();
}
} else {
return function(req, res, next){
// do some other stuff otherwise
return next();
}
}
}
Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?
Express handle this for you!
Also, if you add a property to req or res objects, it will be present in the next middlewares
For example:
router.get('/', (req,res,next) => {
req.customProperty = 'hello!';
return next();
}, (req, res) => {
console.log(req.myCustomProperty)
// hello!
})

Express: Render partially in each handler?

I have a modest little site that uses Express and Pug. Every page has a navbar that contains the user's name drawn from a user parameter and the main content of the page is below which uses a data parameter. The main content is rendered from a template that extends the root template. Both need their own parameter to render properly.
Is there a way to partially render a view in each handler?
var app = require('express')()
app.set('view engine', 'pug')
app.get('/', (req, res, next) => {
var userdata = '...'
req.render('/index', {user: userdata}
next() // the request is for /page
})
app.get('/page', (req, res, next) => {
var moredata = '...'
req.render('./page/index', {data: mroedata})
})
AFAIK that's not possible, but as an alternative, you can use res.locals to achieve something similar:
let userMiddleware = (req, res, next) => {
let userdata = '...';
res.locals.user = userdata;
next();
});
app.use(userMiddleware);
// This can stay the same:
app.get('/page', (req, res, next) => {
var moredata = '...'
req.render('./page/index', {data: mroedata})
})
This is a middleware that will make the user variable available to all of your templates, which seems to me is what you want.
Instead of applying it globally, you can also use it for specific routes:
app.get('/page', userMiddleware, (req, res) => ...);

restify regular expression on named parameter

I am using the restify 2.8.4.
Understood that named parameter with regular expression is not supported in
Mixing regex and :params in route #247
Instead of cobble both logics into one block.
server.get ('/user/:id', function (req, res, next) {
var id = req.params.id;
// check with isNaN()
// if string do this
// if number do that
}
I prefer below code structure:
//hit this route when named param is a number
server.get (/user\/:id(\\d+)/, function (req, res, next) {
var id = req.params.id;
// do stuff with id
}
//hit this route when named param is a string
server.get (/user\/:name[A-Za-z]+/, function (req, res, next) {
var name = req.params.name;
// do stuff with name
}
Is there a way I can split them into two separate concerns?
It looks like you have mostly already done it yourself. Just remove the identifiers from your route and make sure you use regex capture groups.
//hit this route when named param is a number
server.get (/user\/(\d+)/, function (req, res, next) {
var id = req.params[0];
// do stuff with id
}
//hit this route when named param is a string
server.get (/user\/([A-Za-z]+)/, function (req, res, next) {
var name = req.params[0];
// do stuff with name
}
Answer edited to incorporate Cheng Ping Onn's input.