Software Ninja
Software Ninja

Reputation: 135

Cannot set headers after they are sent to the client [dev.start] at ServerResponse.setHeader

I have a REST API using Nodejs and when logging in I get this error in the console:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:481:11)
at ServerResponse.header (/node_modules/express/lib/response.js:767:10)

And in my controller I have the login function:

export async function login(req, res, next) {
  res.status(HTTPStatus.OK).json(req.user.toAuthJSON());
  return next();
}

And here is the Login route:

routes.post(
  '/login',
  validate(AuthenticationController.validation.login),
  authLocal,
  AuthenticationController.login,
);

I tried adding the headers in the main index file:

  app.use ((res) => {
    res.header('Content-Type', 'application/x-www-form-urlencoded')
  })

but the server just hangs. Any help would be appreciated.

Upvotes: 1

Views: 593

Answers (1)

Rajan Panneer Selvam
Rajan Panneer Selvam

Reputation: 1299

You will see this error if your code is trying to respond twice to the same request.

From your code, I suspect the login handler.

export async function login(req, res, next) {
  res.status(HTTPStatus.OK).json(req.user.toAuthJSON()); // Sends the response first
  return next(); // Invokes the next handler, which will also respond
}

To fix this, return immediately after sending the first request.

export async function login(req, res, next) {
  return res.status(HTTPStatus.OK).json(req.user.toAuthJSON()); // Sends the response first
}

Upvotes: 2

Related Questions