Mervin's Blog

Web, mobile, desktop app development, and a little bit of nature...

Node Web Server- HTTP

Created: January 09, 2020

Updated: April 16, 2020

Node is widely used in web applications. So, a simple http server is probably the most sensible starting point. With node's built-in http api, we can readily create an application that takes an http request and sends back a response.

If you don't have a node development environment set-up, you should read Node Development Environment Set-up - For Windows.

Run a powershell terminal, and change to your home directory.

>cd ~/

Create our project directory, and change to that directory.

>mkdir http-server
>cd http-server

Type the following command to initialize our project with default package.json.

>npm init -y

Now, let's open our current folder in visual studio code.

>code .

In visual studio code, open the package.json file. You should see something similar to the following:

1{
2 "name": "http-server",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1"
8 },
9 "keywords": [],
10 "author": "",
11 "license": "ISC",
12}

As you can see, package.json contains data about our project including name, version, and description. This file will also contain a list of our project's dependencies when we start installing packages with npm. The main field is the entry point. It tells visual studio code which file to launch (index.js in this case) when we run or start debugging the program.

We'll name our entry point server.js. So, let's change the value of main field from index.js to server.js. Let's also add a field type and set its value to module, so we can write code in es6 format. The file package.json should now look like the following:

1{
2 "name": "http-server",
3 "version": "1.0.0",
4 "description": "",
5 "main": "server.js",
6 "type": "module",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "keywords": [],
11 "author": "",
12 "license": "ISC"
13}

Create server.js in the root directory of our project then copy and paste the following code:

1// server.js
2import http from 'http'
3
4const httpServer = http.createServer((req, res) => {
5 res.statusCode = 200; // OK
6 res.setHeader('Content-Type', 'text/plain');
7 res.write("Hello world!");
8 res.end();
9});
10
11httpServer.listen(4000, () => {
12 console.debug("HTTP Server running on port 4000.");
13})

On the menubar, click Run -> Start Without Debugging or press Ctrl + F5 on your keyboard to run our program.
Select Node.js from the list of environment, and voila! you have an http server running on port 4000.

Open a browser, and type http://localhost:4000. You should see "Hello world!" displayed on the screen.

Now, let's modify server.js to read some of the request fields and response with a JSON string.

1import http from 'http'
2
3const httpServer = http.createServer((req, res) => {
4 const {method, url} = req;
5 res.statusCode = 200; // OK
6 res.setHeader('Content-Type', 'application/json');
7 const result = {action: method, path: url};
8 res.write(JSON.stringify(result));
9 res.end();
10});
11
12httpServer.listen(4000, () => {
13 console.debug("HTTP Server running on port 4000.");
14})

On the menubar, click Run -> Restart Debugging or press Ctrl + Shift + F5 to restart our server. Go back to the browser and reload the page. You should see the JSON string {"action":"GET","path":"/"} displayed on the screen.

If you want to run the server outside of visual studio, open a terminal and type the following command in our project directory.

>node server.js

That's it pancit!. You now have an http server that reads a request, and sends as response.

Previous

Next