Node Express Throwing Error On Form Resubmission
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.
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. :)
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error