The role of a web server is to service
the user's requests.
The requests are expressed by clicking
links, or occasionally by writing an url in the appropriate
place and then hitting the enter key. The answer of
the server is the response.
The words request
and response is the official
http
terminology.
In this section we shall make another server. Before we make
applications you remember that we generally use npm init
to create the configuration package.json
interactively.
Alter the suggested index.js
starting point to
whatever you call the JavaScript file that
starts the application. Here we use main.js
again.
Put in some remarks
fitting the project into the description.
Finalizing that, the command will present the
file content for your approval.
Your textbook does not use it on page 38, but we do start all
Node.js application by using npm init -y
.
package.json
Resulting from npm init -y
we get
{
"name": "myg51",
"version": "0.9.0",
"description": "Server responding to requests",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Niels Müller Larsen <nmla@iba.dk> (http://dkexit.eu)",
"license": "MIT"
}
Knowing one of the dependencies of the server/application we will build, let us see how to do that and get the configuration file updated in the process. On the command line we write, also for this project
npm i http-status-codes
The dependencies section of the configuration file is changed accordingly.
You already saw a sneak preview of a server in so many lines
of code. Now we will do it again. This time with the necessary
explanatory remarks. Create an application directory,
step into it with cd myg51
and write:
myg51/main.js
"use strict";
const http = require("http");
const httpStatus = require("http-status-codes");
const hostname = "127.0.0.1";
const port = 3000;
const app = http.createServer(); // server as an obj
app.on("request", function (req, res) { // eventhandler for "request"
console.log("Log: Received an incoming request!");
// prep response header
res.writeHead(httpStatus.OK, {
"Content-Type": "text/html; charset=utf-8"
});
// prep response body
let responseMsg = "<h1>This Will Appear on the Screen</h1>";
responseMsg += "<p><kbd>myg51</kbd> at your disposal</p>";
res.write(responseMsg); // respond
res.end(); // sends response http
console.log(`Log: Responded: ${responseMsg}`)
});
app.listen(port, hostname, function () {
console.log(`Server running, and listening at http://${hostname}:${port}/`);
});
On your CLI do node main
. Then go to your
browser and do
http://localhost:3000.