Server Reacting to a Request

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.

Example 16.1. Initial packakge.json
{
  "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 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 and write:

Example 16.2. Your Second Server, 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.