Sending Responses in Node.js
In Node.js, an HTTP response is sent from the server back to the client. We can send plain text, HTML, JSON data, status codes, and headers using the response object provided by the built-in HTTP module.
1. What is an HTTP Response?
An HTTP response is the server's reply to a client's request. It normally contains a status code, response headers, and optionally a response body.
For example, Samadhan opens the CIIT Training Institute website. The Node.js server processes his request and sends a response that the browser can display.
2. Structure of an HTTP Response
Three Important Parts
- Status code: Indicates the result of the request.
- Headers: Provide metadata about the response.
- Body: Contains the actual data sent to the client, when applicable.
3. Setting Status Codes and Headers
The res.writeHead() method sets the HTTP status code
and response headers before the response is sent.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Welcome to CIIT Training Institute!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Terminal Output
Server running at http://localhost:3000
Browser Output
Explanation
200indicates that the request succeeded.Content-Typetells the client how to interpret the response body.text/plainidentifies the body as plain text.res.end()sends the body and completes the response.
4. Sending a Plain Text Response
Use the text/plain content type when the server needs
to return ordinary text.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Hello Samadhan! Your request was successful.");
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Browser Output
The browser displays the text received in the response body.
5. Sending an HTML Response
To return HTML content, set the content type to
text/html.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
res.end(`
<h1>CIIT Training Institute</h1>
<p>Welcome, Pradnya!</p>
<p>Learn Node.js with practical examples.</p>
`);
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Browser Output
CIIT Training Institute
Welcome, Pradnya!
Learn Node.js with practical examples.
text/html content type.
6. Sending a JSON Response
JSON is commonly used by APIs to send structured data.
Node.js provides JSON.stringify() to convert a JavaScript
object into a JSON string.
const http = require("http");
const server = http.createServer((req, res) => {
const student = {
name: "Samadhan",
course: "Node.js",
institute: "CIIT Training Institute"
};
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify(student));
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Browser Output
{
"name": "Samadhan",
"course": "Node.js",
"institute": "CIIT Training Institute"
}
Explanation
- The
studentvariable stores a JavaScript object. JSON.stringify(student)converts the object into JSON text.application/jsonidentifies the response as JSON.- The client can parse the response as JSON data.
7. Difference Between res.write() and res.end()
The res.write() method writes part of the response body.
The res.end() method completes the response and can
optionally send the final body content.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.write("Hello Samadhan! ");
res.write("Welcome to ");
res.end("CIIT Training Institute.");
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Browser Output
| Method | Purpose |
|---|---|
res.write() |
Writes a chunk of the response body without completing the response. |
res.end() |
Completes the response and optionally writes the final data. |
res.end(). The response has already been completed.
8. Common HTTP Status Codes
| Status Code | Meaning | Typical Use |
|---|---|---|
| 200 | OK | Request succeeded. |
| 201 | Created | A new resource was created. |
| 400 | Bad Request | The request contains invalid input. |
| 404 | Not Found | The requested resource was not found. |
| 500 | Internal Server Error | An unexpected server-side error occurred. |
9. Sending a 404 Not Found Response
If the requested resource does not exist, the server should return a suitable status code such as 404 instead of returning success.
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Welcome to CIIT Training Institute!");
} else {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("404 - Page Not Found");
}
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Test URLs
| URL | Status | Response Body |
|---|---|---|
http://localhost:3000/ |
200 | Welcome to CIIT Training Institute! |
http://localhost:3000/courses |
404 | 404 - Page Not Found |
10. Response Execution Flow
11. Common Mistakes
| Mistake | Correct Approach |
|---|---|
Forgetting to call res.end(). |
Complete the response after sending the required body. |
| Sending HTML with a plain-text content type. | Use an appropriate content type such as text/html. |
| Sending a JavaScript object directly as the response body. | Convert the object using JSON.stringify(). |
| Returning 200 for every request. | Use appropriate status codes, such as 404 for missing resources. |
Writing data after res.end(). |
Send all response data before completing the response. |
12. Important Points to Remember
- An HTTP response contains a status code, headers, and optionally a body.
res.writeHead()sets the status code and headers.res.write()writes part of the response body.res.end()completes the response.- Use
text/plainfor plain text andtext/htmlfor HTML. - Use
JSON.stringify()to serialize a JavaScript object as JSON. - Use suitable HTTP status codes to communicate the result of a request.
Summary
In this lesson, we learned how to send HTTP responses using Node.js, set status codes and headers, return plain text, HTML and JSON, use res.write() and res.end(), and handle missing resources with a 404 response. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate practical response handling.