Using the Node.js http module
The http
module is an internal Node.js module. It is, therefore, directly accessible in our programs using the require("http")
instruction. With this module you can create a web server based on the HTTP protocol and thus display web pages in an internet browser.
For creating a web server based on HTTP, we use the http.createServer(callback)
method of the http
module. The callback function indicated as a parameter is of the form callback(req, res)
, in which req
corresponds to the request received, and res
corresponds to the response to be sent to the browser. Depending on the request received, the corresponding response will be sent.
Note
In the req
parameter, there is, among other things, the URL of the request received, thus making it possible to return, via the res
parameter, the correct response to the browser according to this request.
Let’s see in the following program how to use the createServer()
method:
Creating...