Creating a server with Node.js

Creating a server with Node.js

Creating a server without a library

node.js server

To create a server, you need the http/https object, which is built into the core of node.js, and we can import it as a module. There are two module options:

  • http – Http is one of the built-in modules that comes with Node.js and allows creating a server to accept client requests and return responses
  • https – The Https module includes all the basic features of http, but with additional options to handle the necessary security differences like certificates.

When we import one of these two modules, it will return an “http/https” object, as in the following example:

Now that we have the http object we will use it to create a server using the method createServer():

In order for the server to start “listening” for requests, we must start it, this is done by calling the listen() method:

The listen() method accepts four optional parameters, and we will only use the first parameter which defines the port:

The request to the server is sent from this address "http://localhost:3000". To stop the server, we can use its close() method.

Callback for responding to the request of the so-called requestListener()

In the previous example, a server was created, but it does not have any functionality, in order for this server to respond to a request, it is necessary to create an event listener that will listen to requests to the server. We can do that on the standard so-called event-based way with the on():

method

However, this approach is not used most often (although it is completely valid), but a function (so-called requestListener()) is passed as a parameter to the createServer() method, which responds to the request and automatically adds a “request” event.

for simplicity it is best to use the anonymous function:

Accepting GET request and response

Request acceptance

A request object is sent to the server with the request and we can access it through the “request” parameter. It is quite a “big” object that carries a lot of information in its properties and methods, so we can use it for the content of the response body (eg method, url, headers properties):

Parsing the query from the url address

If the sender’s request is specific, he will forward it through the url (eg http://host:8000/?name=Pera), and therefore it is necessary to parse the url and extract data from it. For parsing we will use node.js module “url”.

Server response

a) API based response

To create a basic response (response), we will use the properties of response objects: statusCode and its methods:setHeader(), write() and end():

For the server’s response, we can use some of the data we get from the request object:

The simplest response header is defined in the previous example, here you can see how a standard header can look like.

NOTE:
In the previous example, we can take advantage of the destructuring of the object so that we very simply create variable headers, method and url. See here how the previous example would look when using object destructuring, see more about object destructuring in the article “Destructuring in JavaScript”

b) HTML response

In the previous examples, the responses were the so-called “API based”, but if we want to return html then we will do it similar to the following example:

If in the previous example the url with which the sender sends the request is http://localhost:3000/?name=Pera, then the sender will receive the response “Hello Pera” otherwise it will receive the response “Hello World”.

Receiving data sent with the POST/PUT method

In addition to the get method that visibly sends data within the url, we can “invisibly” send data to the server if we use the POST method. Usually this method is used when we send collected data from a form. In this example, we will generate the form on the server when the client sends a request for a page with the url: http://localhost:3000:

The result of this request on the client looks like this:

POST form

When the user enters the data in the form and clicks the “Save” button, due to the defined HTML attribute “action”, the data from the form will be sent to the page with the url /message, and a new request will be created with it that will forward the data. Collected form data is sent as “readable streams” and may look like this:

What are STREAMS?
Streams are a way to efficiently handle any kind of information exchange (also used for reading/writing files, network communication…). Streams are not a concept unique to Node.js, but have existed within the Unix operating system for decades. Unlike the traditional method where the entire file is loaded into memory and only then processed, here when using streams the program reads part by part of data and processes it simultaneously, thus not burdening the memory at all. In addition to the mentioned advantage where memory is used efficiently because you don’t need to load large amounts of data into memory to be able to process them, there is another advantage called “time efficiency” which reduces the time needed to start processing data, because you can start processing as soon as you get a part of the data, instead of waiting for all the data to be available. Read more about streams in the article Node.js Streams

In order to know at what moment the data is sent and whenthe data transfer is completed, there are registered events for that. “Readable streams” have the following event types registered:

  • data (this event is emitted whenever the stream passes a piece of data called “chunk”)
  • end (this event is emitted whenever the stream has no more data to forward)
  • error
  • close
  • readable

In the following example, we will log on to the “data” event to be notified when the data is being sent, and in order to know when the message ends, we must also log on to the “end” event:

The body variable could look like this after receiving the data:

When we have data in this form, we need to parse it, and for that we will use the node.js module “querystring” and its method parse() transfer data in this form to a collection of “key/value” pairs:

A now readable code will be printed in the console:

Here you can see the entire previous example combined as well as an example in which a buffer (chunk) is concated into a string.

Creating a server with the Express library

Express is a minimalist framework for Node.js that simplifies the process of creating servers and handling HTTP requests. To get started, we first need to install Express using npm:

Once Express is installed, we can import it and use it to create a server. In the following example, we will create a simple server that will respond to a GET request:

In this example, the Express application (app) uses the app.get() method to handle GET requests on the base URL (“/”). The res.send() method sends the response to the client. The server is started using the app.listen() method, which listens for requests on the defined port (in this case, 3000).

Accepting POST requests and sending responses

In addition to GET requests, we can use Express to handle POST requests. In the following example, we will create a route that accepts a POST request and sends a response:

Here we use app.use(express.json()) middleware to parse JSON data from the request body. When the client sends a POST request to the “/data” route, the server will accept the data and send a JSON response back to the client.

Adding routes and error handling

Express makes it easy to add different routes and handle errors. For example, we can add a route for “/about” and create middleware to handle 404 errors:

With this approach, our server can handle different routes and return appropriate responses. Middleware for 404 errors is used to catch all non-existent routes and send the appropriate message to the client.

Express framework offers much more features and flexibility, but these are the basic steps to create a simple server. More information can be found in the official documentation.

×

×

Destructing request object:

×

Example response header:

×

Example of buffer concat

×

Example