Node JS error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

76 Views Asked by At

I am trying to implement authentication in my app. However, app is throwing cannot set header error when registering user. I am not able to wrap my head around why passing thru error handling function "wrapAsync" is thrown this error.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:174:12)
    at done (/Users/alisha/Desktop/Oshi/node_modules/express/lib/response.js:1035:10)
    at /Users/alisha/Desktop/Oshi/node_modules/ejs-mate/lib/index.js:356:7
    at tryHandleCache (/Users/alisha/Desktop/Oshi/node_modules/ejs/lib/ejs.js:280:5)
    at Object.exports.renderFile (/Users/alisha/Desktop/Oshi/node_modules/ejs/lib/ejs.js:491:10)
    at View.renderFile [as engine] (/Users/alisha/Desktop/Oshi/node_modules/ejs-mate/lib/index.js:298:7)
    at View.render (/Users/alisha/Desktop/Oshi/node_modules/express/lib/view.js:135:8)

Here are my code block:

1. /register route:

router.post('/register', wrapAsync(async(req,res)=>{
    const {username, email, nearestLocation, phoneNum, password, RePassword}= req.body;
    if(password !== RePassword) {
        req.flash('error', 'Please retype same password for confirmation')
        return res.redirect('/firm/register')
    }
    
        const hashpw= await bcrypt.hash(password, 12);
        const registerBusiness= new Businesses({
            username: username, email: email, location: nearestLocation, phoneNum: phoneNum,   password: hashpw})
        await registerBusiness.save();
        req.session.currentAccount= registerBusiness.id;
        req.session.currentAccountName = registerBusiness.username;
        req.flash('success', 'Successfully registered your Business account')
        return res.redirect('/home')
}))

2. wrapAsync module:

module.exports = (fn)=>{
    return ((req,res,next)=>{
        fn(req,res,next).catch(next)
    })
}

Can anyone explain this error to me.

I was expecting this block of code to send one response for the request. However, it does not seems to be the case and I am not able to identify how the second response is sent as well. Help me find answer...

1

There are 1 best solutions below

0
On

It was a very simple error from my side. I figured out the problem now. Both router.get and router.post route was sending response to same /register request.