Sending responses
The response object lets you set the status, headers and body you send back.
In this page:
Syntax
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
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
- Setting headers after the body started
- Forgetting Content-Type
- 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: