My experience has been mainly with the Hapi framework for developing RESTful APIs. However, for my current project, I decided to use Express and I'm encountering some confusion regarding the issues that are arising.
While testing the POST endpoint using Postman, everything seems to work fine with the first request, but I encounter an error when attempting a second request.
Error: Can't set headers after they are sent.
The route handler code is as follows:
const login = (req, res) => {
const validation = authScema.loginPayload.validate(req.body)
if (validation.error) {
return res.status(400).send(validation.error.details[0].message)
}
const { email, password } = req.body
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch(error => {
// Handle Errors here.
if (error) {
return res.status(400).send('Invalid login details.')
}
})
firebase.auth().onAuthStateChanged(user => {
if (user) {
const userObject = {
email: user.email,
uid: user.uid
}
const token = jwt.sign(userObject, secret)
return res.status(200).send(token)
}
})
}
I am perplexed by the fact that the headers seem to be resent even though I have returns in every branch. The function should exit at that point, shouldn't it?