HTTP server applications
The HTTP server object is the foundation of all Node.js web applications. The object itself is very close to the HTTP protocol, and its use requires knowledge of that protocol. In most cases, you'll be able to use an application framework such as Express that hides the HTTP protocol details, allowing the programmer to focus on business logic.
We already saw a simple HTTP server application in Chapter 2, Setting up Node.js, which is as follows:
const http = require('http'); http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n'); }).listen(8124, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8124');
The http.createServer
function creates an http.Server
object. Because it is an EventEmitter
, this can be written in another way to make that fact explicit:
const http = require('http'); const server = http.createServer(); server.on('request', (req, res) => { res.writeHead(200, {'Content...