【发布时间】:2021-04-10 16:17:43
【问题描述】:
我的代码和一些中间件有问题。我有一个函数可以获取用户的导航项目列表,并将它们存储在 res.locals 中。但是由于某种原因,我现在遇到了几天前不存在的问题。我的 app.get('/' 函数在中间件承诺完成之前运行。
这是我的路线代码:
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");
};
任何想法为什么这可能不起作用?
【问题讨论】:
-
您在中间件中同步调用 next() - 而 promise 回调是异步执行的。
标签: node.js express middleware