我只是想从适用于路由的中间件中的API获取结果。我正在使用express js res.locals.wallet没有值
var request = require('request');
module.exports = function(req, res, next) {
if(req.session.active){
res.locals.active = req.session.active;
res.locals.email = req.session.email;
// res.locals.wallet = req.session.wallet;
res.locals.admin = req.session.admin;
res.locals.cart = req.session.cart;
res.locals.partner = req.session.partner;
var data = {
user_id :req.session.user_id,
}
request.post({
url : 'https://api.sample.com/frontend/sample',
form : data,
}, function (error, response, body) {
var bodyJson = JSON.parse(body);
console.log(bodyJson);
res.locals.wallet = req.session.wallet; <----- HERES THE PROBLEM
next();
});
} else {
res.redirect("/login");
}
next();
};
答案 0 :(得分:0)
您立即在中间件中调用next
,现在res.locals.wallet
的值为undefined
。
完成工作后只需调用next
(调用api)即可。
var request = require('request');
module.exports = function(req, res, next) {
if(req.session.active){
res.locals.active = req.session.active;
res.locals.email = req.session.email;
// res.locals.wallet = req.session.wallet;
res.locals.admin = req.session.admin;
res.locals.cart = req.session.cart;
res.locals.partner = req.session.partner;
var data = {
user_id :req.session.user_id,
}
request.post({
url : 'https://api.sample.com/frontend/sample',
form : data,
}, function (error, response, body) {
var bodyJson = JSON.parse(body);
console.log(bodyJson);
res.locals.wallet = req.session.wallet; <----- HERES THE PROBLEM
next();
});
} else {
res.redirect("/login");
}
// next(); <----------------- remove this line
};