Creating a Server in Node.js | Lecture 5
Here are
notes on creating a server in Node.js:
Creating a Server in Node.js
What is a Server in Node.js?
- A server in Node.js
listens for incoming requests and sends responses back to the client.
- It uses the http module, which is built into
Node.js.
Steps to Create a Basic Server
- Import the http Module:
- Use the require() function to load the http module.
- Create the Server:
- Use the http.createServer() method to create a new
server instance.
- Define a callback function
to handle incoming requests and responses.
- Specify the Port and Start
the Server:
- Use the server.listen() method to start the server
on a specific port.
Basic Example:
// Step 1: Import the http module
const http = require('http');
// Step 2: Create the server
const server = http.createServer((req, res) => {
res.statusCode = 200; // Set HTTP status code
res.setHeader('Content-Type', 'text/plain'); // Set response content
type
res.end('Hello, Node.js Server!'); // Send response
});
// Step 3: Start the server on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/`);
});
Code Explanation
- http.createServer(callback):
- Creates a server that
listens for incoming HTTP requests.
- The callback function has two
parameters:
- req:
The request object.
- res:
The response object.
- res.statusCode:
- Sets the HTTP status code
for the response (e.g., 200
for success).
- res.setHeader(name, value):
- Sets HTTP headers (e.g., Content-Type for specifying the type of
response).
- res.end(data):
- Ends the response and sends
data to the client.
- server.listen(port,
callback):
- Starts the server on the
specified port.
- The callback runs once the server is
ready.
Enhancements
1. Serve HTML Content:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Welcome to My Node.js Server</h1>');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
2. Basic Routing:
const http = require('http');
const server = http.createServer((req, res) => {
if
(req.url === '/') {
res.end('Welcome to the Home Page');
} else if
(req.url === '/about') {
res.end('Welcome to the About Page');
} else {
res.statusCode = 404;
res.end('404 Not Found');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
3. Serve JSON Data:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const
data = { message: 'Hello, JSON!' };
res.end(JSON.stringify(data));
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
4. Add Logging for Requests:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(`Received request: ${req.method} ${req.url}`);
res.end('Request
logged!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Key Points to Remember
- Port Number:
- Choose a port that is not
in use (commonly 3000 or 8080 for development).
- Request Object (req):
- Contains details of the
client's request, such as method (GET, POST) and URL.
- Response Object (res):
- Used to send data back to
the client.
- Asynchronous Nature:
- Node.js servers are
non-blocking and can handle multiple requests simultaneously.
Let me
know if you’d like to explore advanced topics, like integrating with frameworks
(e.g., Express.js) or connecting to databases!
Comments
Post a Comment