jeudi 26 février 2015

Allow middleware and Route handlers to run together

I can't seem to understand why my custom route handler doesn't pickup the value set within a custom middleware. Here's what I'm working with:


// my route



router.post('/login', bodyParser.text({type: 'urlencoded'}), function(req, res, next) {
if (!req.body) return res.sendStatus(400);
console.log('access token is: ' + req.access_token); // This returns undefined

var options = httpconn.httpOptions({
resource: 'uaa',
resourcePath: '/uaa/authenticate',
method: 'POST',
headers: {'Content-Type': ' application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + req.access_token} // @todo get from the middleware that sets it
});
var httpRequest = application.httprequest(options, function(response) {
response.on('data', function(chunk) {
res.send(chunk);
});
});
httpRequest.on('error', function(e) {
res.status(500);
res.send({'error': 'Authentication Failed: ' + e.message});
return;
});
httpRequest.write(req.body);
httpRequest.end();
});


// custom middleware



router.use(function(req, res, next) {

redisSessionStore.getAsync('active_session').then(function(data) {
req.access_token = data.access_token;
console.log('retrieved access_token: ' + req.access_token);
});
next()
});


If I remove bodyParser.text({type: 'urlencoded'}) from the route, I get a Bad request error.


The custom middleware doesn't seem to run as seen in req.access_token returning undefined.


Any pointers please?


Aucun commentaire:

Enregistrer un commentaire