'Cannot set headers after they are sent to the client in Express js
I'm getting this error while running this code. The API is running fine, after that it is throwing this error.
app.post('/api', async (req, res) => {
try {
channelTwo.consume(queue, async (data) => {
if (data) {
const _data = JSON.parse(data.content);
const SavedData = new User(_data);
await SavedData.save();
channelTwo.ack(data);
if (SavedData) {
res.status(200).json({ message: 'Date Saved to db', SavedData });
}
res.status(400).json({ message: 'Cant save data' });
}
res.status(400).json({ message: 'Cant find data' });
});
} catch (error) {
res.status(400).json({ message: error });
}
})
;
Solution 1:[1]
You have to return after calling res.status(<>).json() otherwise it will be called multiple times.
This will try to set a response header code although already json body has already been sent causing your error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joschi |
