Reputation: 2081
I'm new to node.js and want to send out dataof User
and Match
in a single response by querying mongodb twice .
router.get('/preview/', checkAuth, (req, res)=> {
const errors = {};
const match = {}
User.findOne({_id: req.user.id})
.then(user => {
if (!user) {
return res.status(404).json({errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id }).then(m => {
console.log('match found!');
match = m;
}).catch(err=> res.status(404).json(err)); // <-error occures here
res.status(200).json({user, match});
})
.catch(err=> res.status(404).json(err));
});
But I get this error:
(node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
How can I fix it?
Upvotes: 0
Views: 220
Reputation: 1371
Please have a look at the comments added in your code.
router.get('/preview/', checkAuth, (req, res)=> {
const errors = {};
const match = {}
User.findOne({_id: req.user.id})
.then(user => {
if (!user) {
return res.status(404).json({errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id }).then(m => {
console.log('match found!');
match = m;
}).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs
res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
})
.catch(err=> res.status(404).json(err));
});
Improved code:
router.get('/preview/', checkAuth, (req, res) => {
const errors = {};
User.findOne({ _id: req.user.id })
.then((user) => {
if (!user) {
return res.status(404).json({ errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id })
.then((m) => {
console.log('match found!');
res.status(200).json({ user, m }); // send the success response when the match found
})
.catch((err) => res.status(404).json(err)); // send the error response when erro thrown
})
.catch((err) => res.status(404).json(err));
});
Upvotes: 2