Simple HTTP Server

It is time to start coding and see how we can implement a simple HTTP Server using Node.js. So, open your Terminal and in the working directory of your choice, go ahead and create a new folder called my-server:

$ mkdir my-server
$ cd my-server

Once you move into the my-server folder, we will need to initialize an NPM module, so run the following command:

$ npm init -y

{
"name": "my-server",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}

Now it's time to create the server.js file by executing the touch server.js command in your Terminal. This file will contain the code for our server. We will start importing the HTTP module:

const http = require('http')

We import any module using the require built-in function, and we define the http variable to house the module reference. Let's implement a simple handler by writing the following code:

const myRequestHandler = (request, response) => {
response.end('Hello From our Node.js Server !!')
}

As you can see, a handler is just a function that declares two parameters:

  • request: Used to read the information sent by the client
  • response: Used to send information to the client

Our handler is using the response parameter to send our friendly message to the client. Now it's time to create a server instance using the http reference we declared earlier:

const server = http.createServer(myRequestHandler)

We are creating an empty server that does not perform any operation. To make our server useful, we pass the request handler we declared earlier, myRequestHandler. With this, our server is able to send our Hello message every time some client sends an HTTP request to our server. To finish our server implementation, we need to listen to the client request:

server.listen(5000, () => {
console.log("server is running on port 5000")
})

That's all! Now that we have a simple HTTP, execute the node server.js command to run the server. Let's test things out. Head over to http://localhost:5000 and you should see something like the following:

Now you know how to create a simple HTTP server using the native HTTP module that comes along with Node.js. However, in order to create a powerful RESTful backend, we need to use a more sophisticated framework.

In the next section, we will enhance our simple server using Express.js.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset