gpt4 book ai didi

node.js - 如何从中间件获取api结果到路由

转载 作者:太空宇宙 更新时间:2023-11-03 22:20:24 25 4
gpt4 key购买 nike

我只是想从适用于路由的中间件中的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();
};

最佳答案

您在中间件中立即调用next,现在res.locals.wallet值是未定义

完成工作后只需调用 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
};

关于node.js - 如何从中间件获取api结果到路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56681077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com