← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 3 of 7

Sending responses

The response object lets you set the status, headers and body you send back.

In this page:

  1. Sending responses
Syntax
javascript
res.writeHead(statusCode, { 'Content-Type': 'type' });
res.write('chunk');
res.end('body');

Sending responses

res.writeHead(status, headers) or res.statusCode and res.setHeader set metadata, and res.end(body) finishes the response. For JSON, set Content-Type to application/json and stringify the data.

Note: Set headers before writing the body.

Example: Sending responses

javascript
const http = require("http");
const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ ok: true, path: req.url }));
});
server.listen(0, () => {
  http.get({ port: server.address().port, path: "/api" }, (res) => {
    console.log(res.statusCode, res.headers["content-type"]);
    res.on("data", (c) => console.log(String(c)));
    res.on("end", () => server.close());
  });
});

// Output:
// 200 application/json
// {"ok":true,"path":"/api"}

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Setting headers after the body started
  2. Forgetting Content-Type
  3. Calling end twice
Chapter Summary
  • writeHead sets status and headers
  • end sends the body
  • JSON needs Content-Type
  • Set headers first
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.