We create an HTTP server to listen for requests from web browsers or other clients and send back responses like web pages or data.
Creating a basic HTTP server in Node.js
import http from 'http'; const server = http.createServer((req, res) => { // handle request and response here }); server.listen(3000, () => { console.log(`Server running on port 3000`); });
The http.createServer function creates a server that listens for requests.
The callback receives req (request) and res (response) objects to handle communication.
import http from 'http'; const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen(3000);
import http from 'http'; const server = http.createServer((req, res) => { if (req.url === '/') { res.end('Home page'); } else { res.statusCode = 404; res.end('Not found'); } }); server.listen(8080);
This program creates a simple HTTP server on port 4000. It sends a plain text message 'Welcome to my server!' for every request. When the server starts, it logs a message to the console.
import http from 'http'; const port = 4000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Welcome to my server!'); }); server.listen(port, () => { console.log(`Server running on port ${port}`); });
Always set the correct Content-Type header so browsers know how to display the response.
Use res.end() to finish the response and send data back to the client.
Remember to choose a port number that is free and allowed by your system.
Creating an HTTP server lets your computer respond to web requests.
Use http.createServer with a function to handle requests and responses.
Start the server with server.listen(port) and check the console for confirmation.