简体   繁体   中英

next(err) not working in node.js

I have the issue that my next(err) is not working. It ignores error and just loads the page instead of sending HTTP status code 404.

The ldap search works fine and result looks as expected. It just doesn't return error when the else statement is hit. The console does show the failed in log

app.use(function(req, res, next){
    conn.search('dc=foo', opts, function (err, res) {

        assert.ifError(err)
        var entries = []

        res.on('searchEntry', function (entry) {

            entries.push(entry.object)
        })

        res.on('end', function (result) {

            conn.unbind(function (err) {

                console.log('Disconnecting')

                if (entries.length == 1) {
                    next()
                } else {
                    console.log('fail')
                    var err = new Error('Permission Denied')
                    err.status = 404
                    next(err)
                }
            })
        })
    })
})

I don't think next works like that. If you do not want your next middleware to be called, don't call next(error) or next() at all. Use instead :

if (entries.length == 1) {
     next()
} else {
     console.log('fail')
     return res.status(404).send('Permission Denied')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM