Thursday, September 1, 2022

node.js: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

 

>PROBLEM


A request generates the following error:

  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


>SOLUTION


It happens when some exception occurs before returning the request, for instance a "res.sent" statement.

Debug the application step-by-step.

To simplify, you may comment on the code from the start.

Tip: check database exceptions not treated.

Having more than one exception becomes tricky if you can't reproduce the same request.


Be sure to fix all possible exceptions.

TIPS

- Verify database possible exceptions (undefined/null values).
- If using JWT, check possible "jwt session expired" exception.
- "if conditions" and "redirections".
Some if conditions may not avoid running the code ahead from it.
- Make sure that you have guarded your arguments checking if they are possibly null or undefined.
- Unexpected type values.
 JavaScript is not a typed language, so part of the code may get something different from expected.

The above tips are just some of them. 


>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


No comments:

Post a Comment

eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...