11. Node.js. Lessons. Echo-server.

nodejs-avanzado

Hey all! This lesson will be devoted to the echo server creation. This is a server that brings up the parameter meaning upon the url/echo request with the message parameter:

The answer to all other requests will be: Page Not Found.

Let us start from a template of this kind:

A server is created and then given a function – a request handler. The first step for the request handling is to understand what kind of a request we’ve received. For that reason we use method and url properties of the request object. Add to your function body:

I launch and enter a browser to this page. Note: I followed this url:

http://127.0.0.1:3000/echo?message=Hello

and using console.log it outputted that the method is called GET, as well as the requested subject: GET /echo?message=Hello

I switch back to the browser and see that nothing has been outputted. Browser is waiting for something. For a response! It happens because a server, if no clear command is given or no response is written, will do nothing. And that is the main difference of Node.js from many existing servers. It does only those things with the connection that you order it to do. If you don’t tell the server “send back a response,” it will send nothing back. Respectively, it turns out that the connection exists, the request function has been used, but it did nothing to respond – that’s why your request got hung up. And it will hang up for as long, as your browser or server will tell it to. Whatever considers this too annoying – that element will cut the connection off.

So, let us respond with a message that we’ve received in a message parameter. To do so, I need to clearly understand what is contained in the message. Let me remind you our task. If url looks like:

/echo?message=Hello

and there is a message parameter, you need to send its value. Otherwise you will receive: Page Not Found. Respectively, to clear up our url, you can use regular expressions. But Node.js has a specialized url module for that purpose, so let us add it:

I use it to dismantle the transmitted request string. This method is called url.parse:

Start the server and update the page. You can see our request in the terminal. We are primarily interested in query and pathname parameters. Let us describe them in the same function.

We’ve also got a message parameter. So, how can you understand whether there is a message parameter, since query is a string? The easiest way is to add one more argument to the url.parse command that will make this string an object, if true is specified:

Respectively, message will be its value:

If all these elements are there, let us respond:

But what if not? Then leave a response: Page Not Found. To do so, you need to leave a respective response code and the page body:

So, you will get:

Restart your server and open the browser. Everything works.

Now let us enter following another url: Page not found. If I open a folder named Network, here we will see that Page not found has a response code 404, while a regular url has a standard response code 200.

So, the echo server is ready and working. It was really vital for us to start it up because an echo server is a prototype of a real-world app. Real apps receive requests of different types and respond them.

Our next theme is Work with Headers. I would ask you to be extremely attentive here, especially if you are a beginner in server development and you’ve gained your experience predominantly in client development.

When a browser makes a request, it adds extra information sent with url. This information clarifies what kind of browser it is, as well as certain details of its request. The information has a special format called as “headers” and is available in the following form: req.headers.

Let us add comments to the code for better understanding. So, we will see:

We launch it, follow the page and see a header in the terminal sent by the browser. Each header has its name and value. Note that every Node.js header has a lower-case name. That is Node.js specifics. In our case, host gets transmitted to headers, connection – keep-alive means that the browser wanted to transmit new requests again and again using this network connection – the thing we’ve talked about earlier: Connection – one, request  many.

Further we see the details of what this browser is and what it would like to receive. Responding this request the browser surely uses the page body and headers as well, where it puts the status. It is generally “200.” This status is called “OK” by default and means the page was normally generated. Let us uncomment our code. Add the following to “if”:

Another popular status is “404”, which is commonly called not found  Page Not Found. There are other statuses like, for example, 403 – Forbidden, 500 – Internal Server Error. There are other server headers, too. Let us restart the server:

The Network folder, i.e. Headers, contains all these headers. There are headers sent by your browser, as well as those received by your browser from the server. Click “view source” to have a clearer understanding. You will see additional headers, their more detailed view. OK Status, as we’ve previously said, together with a number of other headers are quite standard here.

Let us put some other, the most important server headers, which are usually put manually. These are the headers dealing with the content or caching types. For example, if I’m working on a web service, I may want to leave the service response results caching-free. To do so, I will put the header cache-control, no-cache. You can make it even more favorable by adding more options, but let us use this short variant for our example:

Let us launch the server and look in a browser window what’s going on with our headers. The changes are quite obvious: an additional header cache-control, no-cache has appeared, i.e. the one we’ve sent.

There are many other headers you can learn about in the http protocol descriptions, in various caching tutorials, etc. We will meet some other headers further in our lessons, too, when we need them.

For now, let us get a little bit away from general http and get back to Node.js. To work with headers, the res. response has two cardinally different methods. The first one is given here:

The status code is added, and setHeader or removeHeader adds or removes the header. At the same time, the very headers will be sent to a server not simultaneously upon adding setHeader, but together with the upcoming data writing – for example, res.end request sends the respond and headers, too. The second header management way is called as “clear.” It looks like:

It differs from others with a thing that headers are written together with responses, not waiting when the nearest note begins. Sometimes this type is needed, too. But generally the following types of headers is enough: status code and setHeader.

You can find this lesson’s coding in our repository.

echodeveloplogo

The lesson’s materials were borrowed from the following screencast.

We are looking forward to meeting you on our website soshace.com

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

How I Built an Admin Dashboard with Python Flask

In this article, I will share the how I built an admin dashboard. I will give a step by step guideline on how I built this application with Python ...

Getting started with Git Hooks using ghooks

Git hooks are configured scripts that are executed at specific moments during git operations. ghooks is a package that configures git hooks so that ...

React Native vs. Flutter: Which One Would Suit You Better?

Unveiling pros and cons of such cross-platform development frameworks as Flutter and React Native. Discover what suits you ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy