-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode4.xt
More file actions
105 lines (60 loc) · 1.59 KB
/
Copy pathnode4.xt
File metadata and controls
105 lines (60 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
Chapter 4 – HTTP Module & Creating a Basic Server
1. What is the HTTP Module?
Node.js has a built-in module named http that allows you to:
Create a server
Handle requests & responses
Send data to the browser
Build APIs
No installation needed:
const http = require("http");
2. Creating a Simple Server
A server listens for requests and sends back responses.
Basic structure:
http.createServer((req, res) => {
res.write("Hello from Node.js Server");
res.end();
}).listen(3000);
req → request from the client
res → reply from server
.listen(3000) → server starts at port 3000
3. Request & Response Explanation
Request (req)
Contains:
URL (/home, /about)
HTTP Method (GET, POST)
Headers
Response (res)
Used to send:
text
HTML
JSON
status codes
Example:
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Success");
4. Serving HTML Content
You can send HTML directly:
res.write("<h1>Welcome</h1>");
Or you can read HTML files and send them using fs module.
5. Routing in Node.js (Without Express)
You can manually create routes:
if (req.url === "/") {
res.end("Home Page");
}
else if (req.url === "/about") {
res.end("About Page");
}
else {
res.end("404 Page Not Found");
}
6. Sending JSON Response
const data = { name: "Mounika", language: "Node.js" };
res.end(JSON.stringify(data));
7. Summary of This Chapter
By completing Chapter 4, you understand:
What HTTP module is
How to create a Node.js server
Handling requests and responses
Sending HTML and JSON
Basic routing without Express
This is the foundation for building backend systems and APIs.