In the process of mastering node.js on lessons in the network, I encountered such a phenomenon as routing.

I don't understand its essence, but explain it everywhere using the example of the Express framework, which only adds complexity.

I installed the router module through npm into my application stub , went to read the readme, and there: Router requests.

I appreciated the humor, but I did not understand how to figure it out. I ask you to stick in a good lesson on routing without frameworks. To not just "how", but "why." It is desirable in Russian, but there as it turns out.

Well, or suddenly not too lazy for anyone to briefly and eloquently describe how the router is generally used.

In general, I will accept any info on a bare node.

  • one
    Routing in the sense of "handling http requests" is merely installing handlers for the paths you need. Those. just a procedure that needs to be performed if a request is sent to ru.stackoverflow.com on the / questions / 748410 way, for example. Usually in this case, the server sends an HTML document in response, but in general the server’s response can be arbitrary. - Artyom Ionash

1 answer 1

I understand that we are talking about this lib.

I ask you to stick in a good lesson on routing without frameworks.

So this library works without any frameworks, on top of the standard http .

Well, or suddenly not too lazy for anyone to briefly and eloquently describe how the router is generally used.

You can do without it:

 const http = require('http'); const srv = http.createServer(function(req, res) { var uri = req.url; // вот тут у вас лежит теперь url, по которому пользователь обратился }); srv.listen(8080); 

Actually everything, now you can handle uri as you please.

If you use a router:

 route.get('/', function(req, res) { // этот метод сработает, если пользователь открыл корень сайта }); route.get('/{x}x{y}', function(req, res) { // если пользователь открыл your_site/200x200, сработает этот метод // в req.params будет {x:'200', y:'200'} }); 

Here is the addition of rules for the router. When a request comes from a user, the router checks the request with the list of rules that you gave him and calls the necessary callback to your logic.

The router simply simplifies the work. There is no need to parse the request, etc.

  • Do I understand correctly that for each specific case we create a separate structure in the server's callback like this? route.get('/', function(req, res) { // этот метод сработает, если пользователь открыл корень сайта }); - Aleksandr Shemetillo
  • one
    @AleksandrShemetillo can be grouped. You can use regular expressions to create a route on every path. - Suvitruf
  • Thanks, set up the first similarity of routing with your help. - Aleksandr Shemetillo