0
0
NodejsDebug / FixBeginner · 4 min read

How to Handle Response in Node.js: Fix Common Mistakes

In Node.js, handle HTTP responses by using the res object methods like res.write() and res.end() to send data back to the client. Always ensure you end the response with res.end() to avoid hanging requests.
🔍

Why This Happens

When handling HTTP responses in Node.js, forgetting to call res.end() or misusing response methods causes the client to wait indefinitely or receive incomplete data. This happens because Node.js streams the response and needs a clear signal to finish sending data.

javascript
const http = require('http');

http.createServer((req, res) => {
  res.write('Hello, world!');
  // Missing res.end() here
}).listen(3000);
Output
The client request hangs and never completes because the response is not ended.
🔧

The Fix

Always call res.end() after writing data to the response to signal that the response is complete. You can also send the entire response at once using res.end() with data.

javascript
const http = require('http');

http.createServer((req, res) => {
  res.write('Hello, world!');
  res.end();
}).listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server runs and client receives 'Hello, world!' then connection closes properly.
🛡️

Prevention

To avoid response handling errors, always:

  • Use res.end() to finish responses.
  • Use res.writeHead() to set status and headers before sending data.
  • Consider using frameworks like Express.js that simplify response handling.
  • Enable linting rules to warn about missing res.end() calls.
⚠️

Related Errors

Common related errors include:

  • Cannot set headers after they are sent: Happens if you try to send headers or data after calling res.end().
  • Unhandled promise rejections: When using async code, forgetting to handle errors can cause crashes.

Key Takeaways

Always call res.end() to properly finish HTTP responses in Node.js.
Use res.writeHead() to set headers before sending data.
Avoid sending data after ending the response to prevent errors.
Consider using Express.js for simpler and safer response handling.
Enable linting to catch missing response end calls early.