Creating a Server
Building on the http module, a Node.js server listens on a port and responds to incoming client requests, such as web browsers or API clients.
Once a server is listening, it stays running, handling requests one after another using the event loop.
Listening on a port
`server.listen(port, callback)` starts the server and optionally logs a confirmation once it's ready.
Handling different requests
Inside the request handler, you inspect `req.url` and `req.method` to decide how to respond differently to different requests.
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.method, req.url);
res.end('OK');
});
server.listen(3000, () => console.log('Listening on port 3000'));Listening on port 3000
GET /The server logs each request's method and URL, then responds with 'OK'.
server.listen(3000, '127.0.0.1', () => {
console.log('Server bound to localhost');
});Server bound to localhostYou can also specify a hostname to bind the server to.
Key points
- server.listen() starts the server on a given port.
- req.url and req.method identify what the client requested.
- The server keeps running and handling requests via the event loop.
- You can bind a server to a specific hostname/IP.
