http
ModuleThe http
module in Node.js allows us to create HTTP servers and handle HTTP requests and responses.
It’s a core module, so no extra installation is needed — you can import it using:
const http = require('http');
Import the http
module
const http = require('http');
Define the port number
const PORT = 3000;
Create the server instance
http.createServer()
to create a new server.const server = http.createServer();
Start the server using listen()
listen()
method starts the server and begins accepting connections.server.listen(PORT, () => {
console.log(`Server is running at <http://localhost>:${PORT}`);
});
localhost
and the URL?localhost
refers to your own computer — it’s a hostname that means "this machine".http://localhost:3000
points to:
http://
→ The protocol being used (HyperText Transfer Protocol)localhost
→ The server running on your own system3000
→ The port number your server is listening onIf your server is running on port 3000
, you can access it by visiting:
<http://localhost:3000>
in your browser or using a tool like Postman.