Greetings. I'm encountering the "Cannot set headers after they are sent to the client" error when trying to use res.redirect.
This specific section of the code is triggered by a verification email. Everything works smoothly until the redirect step, which then triggers the error.
@Get('/validate')
async validate(
@QueryParam('token') token: string,
@Res() res: Response,
): Promise<void> {
const usersByToken = await (this.repository as UserRepository).getByToken(token);
let isvalid = false;
if (usersByToken.length !== 1) {
isvalid = false;
}
if (!isBlacklisted(usersByToken[0].email)) {
const uni = isUniversity(usersByToken[0].email);
const organizationcontroller = new OrganizationController();
const org = await organizationcontroller.getByName(uni);
if (!org) {
await sendAdminEmail(usersByToken[0].email);
isvalid = false;
} else {
const update = await (this.repository as UserRepository).validateUser(token, org);
if (update.affected > 0) {
isvalid = true;
}
}
} else {
isvalid = false;
}
if (isvalid) {
return res.status(200).redirect(`/login;validation=ok;email=${usersByToken[0].email}`);
} else {
return res.redirect('/login;validation=invalid');
}
}
Here is the corresponding error message:
Error: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (D:\Egyetem\szakdoga\backend\node_modules\express\lib\response.js:776:10)
at ServerResponse.json (D:\Egyetem\szakdoga\backend\node_modules\express\lib\response.js:264:10)
at ExpressDriver.handleError (D:\Egyetem\szakdoga\backend\node_modules\src\driver\express\ExpressDriver.ts:377:18)
at D:\Egyetem\szakdoga\backend\node_modules\src\RoutingControllers.ts:128:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Based on the code flow, it seems like no other response is being sent, so determining the cause of the error is challenging.