First, ensure that Node.js is installed on your system. You can check by running:
node -v
To create a new project, run:
mkdir node-http-server && cd node-http-server
npm init -y
Create a new file server.js
and add the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js HTTP Server!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
💡 Explanation:
http.createServer()
method creates a server.req
object handles incoming requests.res
object is used to send responses.Run the server:
node server.js
Modify server.js
to handle multiple routes:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url === '/') {
res.end('<h1>Welcome to the Home Page</h1>');
} else if (req.url === '/about') {
res.end('<h1>About Us</h1>');
} else {
res.writeHead(404);
res.end('<h1>404 - Page Not Found</h1>');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Modify server.js
to return JSON responses:
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
if (req.url === '/api') {
const data = { message: 'Hello, API!', status: 200 };
res.end(JSON.stringify(data));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
Instead of hardcoding the port, use an environment variable:
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
A Node.js HTTP server is fundamental for handling web requests. This guide covered:
✅ Setting up a basic HTTP server
✅ Handling multiple routes
✅ Returning JSON responses
✅ Using best practices like environment variables
\
@asadmukhtar