Ad

Node Express Throwing Error On Form Resubmission

- 1 answer

I am new to express. I am writing a demo authentication.

But it shows this error

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

when form re-submission happens. If i use a request logger than it shows that I get one post request. but the callback function on form.parse gets called twice. I just can't figure it out why is this happening.

router.post('/signup', (req,res)=>{
    form.parse(req, (err, fld)=>{
        if(err) throw err;
        let name = fld.name;
        let pass = fld.password;
        let checkUser = users.filter(item=>{ item.name == name })


        if(checkUser.length >0){
            res.render('form.html', {err: 'Username Exists!'});
            console.log('**') // this line prints twice when a from is resubmitted
        }else{

            let user = new User(name, pass);
           users.push(user);

            save(users, './user.json', ()=>{
                res.end('you can log in now');
            });
        }

    })
})

I am using ejs as view engine. users is a array of user object.save is a function to write json files. they are just working fine.

Ad

Answer

I think I got the answer. The problem was with the creation of the formidable from obejct. What i did wrong was I created the form object at the beginning of the script. Which made the form object global and caused the trouble.

let form = new formidale.IncomingForm()

I had to create new form form objects for each post request separately, that is I had to put this line inside the route.

router.post('/signup', (req,res)=>{

    let form = new formidable.IncomingForm(); // this is where it should belong

    form.parse(req, (err, fld)=>{
        if(err) throw err;
        let name = fld.name;
        let pass = fld.password;
        let checkUser = users.filter(item=>{ 
            return item.name == name            
        })


        if(checkUser.length >0){
            res.render('form.html', {'err': 'Username Exists!'});
            console.log('2');

            return
        }else{
            console.log(3);

            let user = new User(name, pass);
           users.push(user);

            save(users, './user.json', ()=>{
                res.end('you can log in now');
            });
        }

    })
})


Now it works fine.

I hope this answer to my own question helps someone out there sometime. :)

Ad
source: stackoverflow.com
Ad