中间件调用下一个但程序仍然挂起

时间:2018-05-15 22:04:13

标签: javascript node.js express routing middleware

我写了一些简单的中间件,在每个请求上向请求对象添加内容。无论在哪个路径下,流都需要调用,但是响应永远不会,因此我之后定义的所有路由都无法访问。我的代码有问题吗?

中间件是:

module.exports = (db) => {
    return function(req, res, next) {
        if(req.isAuthenticated()){
            debugger;
            db.user.findOne({where:{id:req.user.id}})
                .then((user)=>{
                    //set user permission
                    if(user.permission_id === 1){
                        //user is an Client
                        req.userIdentity = 'client';
                    }else if(user.permission_id === 2){
                        //user is a Coach
                        req.userIdentity = 'coach';
                    }else if(user.permission_id === 3){
                        //user is Admin
                        req.userIdentity = 'admin';
                    }

                    //set user status
                    if(user.user_status_id === 1){
                        req.userStatus = 'active';
                    }else if(user.user_status_id === 2){
                        req.userStatus = 'inactive';
                    }else if(user.user_status_id === 3){
                        req.userStatus = 'pending';
                    }

                    next();
                });
        }
        else{
            return next();
        }
    }
};

我在app.js中这样称呼它:

 app.use(passport.initialize());
 app.use(passport.session());
require('./services/passport');

//get identity of user. ie client, coach, or admin
const userIdentity =require('./services/userIdentity');
app.use(userIdentity(db)); <====== this is the middleware

//initiate route handlers
app.use('/login', require('./routes/authRoutes'));
app.use('/tiles', require('./routes/tileRoutes'));
app.use('/user-info', require('./routes/userRoutes'));

//this path MUST stay below other route handlers
app.get('*', (req, res)=>{
    res.sendFile(path.join(__dirname, './client/build/index.html'));
});

UPDATE **** 已添加.catch(err=>res.send(err)); 看看是不是,但事实并非如此。我使用调试器语句来逐步执行代码,数据库调用肯定会返回它应该的内容。我的if / elses都适当地逐步通过,然后没有,应用程序就停止了。

0 个答案:

没有答案