我似乎无法理解为什么我的自定义路由处理程序无法获取自定义中间件中的值集。以下是我正在使用的内容:
//我的路线
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();
});
//自定义中间件
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()
});
如果我从路线中删除bodyParser.text({type: 'urlencoded'})
,则会收到错误请求错误。
自定义中间件似乎没有像req.access_token中看到的那样运行返回undefined。
请指点什么?
答案 0 :(得分:0)
next()
放置不当。它应该是:
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()
});
});