How to prevent further execution of Express middleware
P粉674999420
P粉674999420 2024-01-02 11:41:53
0
1
444

I want to get this function if(thereIsSomeError) //Stop further execution. For example if some error occurs in middleware or callback then I don't want to execute callback (in app.route) and middleware further I tried this code. But I still think req.err is true. How can I solve this problem

// My MiddleWare
export let Middleware=()=> {
return (req,res,next)=>{
    next()
    console.log(req.err) // Problem is here.. i'm still getting req.err(true)
    if(!req.err){
        db.query(`query`,(error, responseData)=>{
            if(error) console.log(error)
            db.query(`second query`,{...// send data to the 
database})
        })
        }
    }
}



//End point    
app.post('/addStudent',Middleware, (req, res) => {
//setting error to true initially
    req.err=true;
    let data = req.body
    db.query(`query `, data.username, (err, d) => {
        if (err) return res.json(err)
        else {
        // since no Error accured so set the error to false
        req.err=false;
            let q = 'query';
            let values = {//data here}

            db.query(q, values, (err, data) => {
                if (err) return res.status(200).json(err)
                else return res.status(200).json({ data })
            })
        }
    })
})


P粉674999420
P粉674999420

reply all(1)
P粉198814372

First of all, middleware runs before the request, not after. If you set req.err = true in the POST endpoint, it will remain TRUE, which means your database calls will definitely return an error.

Second, to successfully abort the middleware call, use return. Returning a function immediately stops it. You can choose to return next(err) to forward the error to a handler, or use return res.send('Error') to terminate the response middleware.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template