angularjs - Getting error "Cant set headers after they are sent" when trying to upload image and user data to mongoDB -
i using node, express, mongo , angular make simple app. have form user can insert data , upload image. image upload use ng-file-upload. using multiparty form data. here api upload of image server folder , save , entry in mongdb of user data along filename.
router.route('/upload/image') .post(function(req, res){ var form = new multiparty.form(); form.parse(req, function(err, fields, files) { console.log(files); console.log(fields); var file = files.file[0]; var contenttype = file.headers['content-type']; var tmppath = file.path; var extindex = tmppath.lastindexof('.'); var extension = (extindex < 0) ? '' : tmppath.substr(extindex); // uuid generating unique filenames. var filename = uuid.v4() + extension; var destpath = './public/img/' + filename; // server side file type checker. if (contenttype !== 'image/png' && contenttype !== 'image/jpeg' && contenttype !== 'image/jpg') { fs.unlink(tmppath); return res.status(400).send('unsupported file type.'); } fs.rename(tmppath, destpath, function(err) { if (err) { return res.status(400).send('image not saved:'); } return res.json(destpath); }); var user = new user(); user.firstname = fields.firstname; user.lastname = fields.lastname; user.email = fields.email; user.numofcups = fields.numofcups; user.currentbalance = fields.currentbalance; user.totalnumofcups = fields.numofcups; user.totalmoneyspent = fields.currentbalance; user.photo = destpath; user.save(function(err, user){ if(err){ return res.send(500, err); } return res.json(user); }); }); });
when save user data in ui copies file server folder not save data mongodb , throw error - "cant set headers after sent". it has res.json
being called twice, how solve this? pointers appreciated.
you cannot send multiples responses.
fix: remove return res.json(destpath);
, put code creation of user saving entity, in place of return res.json(destpath);
Comments
Post a Comment