Node.js 在中间件承诺完成之前运行的路由
我的代码和一些中间件有问题。我有一个函数,可以为用户获取导航项列表,并将它们存储在res.locals中。然而,出于某种原因,我现在遇到了一个几天前还没有出现的问题。My app.get(“/”函数在中间件承诺完成之前运行 这是我的路线代码:Node.js 在中间件承诺完成之前运行的路由,node.js,express,middleware,Node.js,Express,Middleware,我的代码和一些中间件有问题。我有一个函数,可以为用户获取导航项列表,并将它们存储在res.locals中。然而,出于某种原因,我现在遇到了一个几天前还没有出现的问题。My app.get(“/”函数在中间件承诺完成之前运行 这是我的路线代码: const isAuthenticated = require("../config/middleware/isAuthenticated"); module.exports = function(app) { app.ge
const isAuthenticated = require("../config/middleware/isAuthenticated");
module.exports = function(app) {
app.get('/', isAuthenticated, function(req, res) {
res.locals.title = 'Welcome';
res.render('index.ejs');
});
}
我的中间件:
// This is middleware for restricting routes a user is not allowed to visit if not logged in
const Utils = require('../../models/Utils/utils');
module.exports = function(req, res, next) {
// If the user is logged in, continue with the request to the restricted route
if (req.user) {
res.locals.user = {first_name: req.user.first_name, last_name: req.user.last_name};
if(!res.locals.nav) {
let navPromise = Utils.createNavs(req.user.id);
navPromise.then(function(navItems) {
res.locals.nav = navItems;
});
}
return next();
}
// If the user isn't' logged in, redirect them to the login page
return res.redirect("/login");
};
你知道为什么这可能不起作用吗?根据我上面的评论,这应该能更好地发挥作用-即只有在
navPromise
问题解决后才调用下一个中间件/路由
module.exports = function(req, res, next) {
// If the user is logged in, continue with the request to the restricted route
if (req.user) {
res.locals.user = {first_name: req.user.first_name, last_name: req.user.last_name};
if(!res.locals.nav) {
let navPromise = Utils.createNavs(req.user.id);
navPromise.then(function(navItems) {
res.locals.nav = navItems;
next()
});
}
return;
}
// If the user isn't' logged in, redirect them to the login page
return res.redirect("/login");
};
根据我上面的评论,这应该可以更好地工作-即只有当
navPromise
解决了问题时,才调用队列中的下一个中间件/路由
module.exports = function(req, res, next) {
// If the user is logged in, continue with the request to the restricted route
if (req.user) {
res.locals.user = {first_name: req.user.first_name, last_name: req.user.last_name};
if(!res.locals.nav) {
let navPromise = Utils.createNavs(req.user.id);
navPromise.then(function(navItems) {
res.locals.nav = navItems;
next()
});
}
return;
}
// If the user isn't' logged in, redirect them to the login page
return res.redirect("/login");
};
您正在中间件中同步调用next(),而promise回调是异步执行的在您的中间件中同步-而promise回调是异步执行的。非常感谢!现在来了解为什么路由会被调用两次。非常感谢!现在来了解为什么路由会被调用两次。