I'm trying to do something like this,
// /api/auth
const validateFields = ({ name, email }, res) => {
if (!name.trim()) return res.status(422).json({ error: 'name' })
if (!email.trim()) return res.status(422).json({ error: 'email' })
}
router.post('/', async (req, res) => {
const { name = '', email = '' } = req.body
validateFields({ name, email }, res)
return res.end()
})
If someone passes an invalid name or email, let's say an empty string, the frontend received the expected error, but the backend (ExpressJS) throws an error,
Error: Can't set headers after they are sent
I'm kind of forced to do the following,
const validateFields = ({ name, email }, res) => {
if (!name.trim()) return res.status(422).json({ error: 'name' })
if (!email.trim()) return res.status(422).json({ error: 'email' })
return true
}
router.post('/', async (req, res) => {
const { name = '', email = '' } = req.body
const validFields = validateFields({ name, email }, res)
if (validFields !== true) return
return res.end()
})
Is this my only option here?