I start by saying that app.get
is a normal function that gets two parameters: A path in the form of string
and a callback. You can then view this function as follows:
app.get(caminho, callback);
In your example the path is '/'
and the callback is function(req, res){res.send('Ola Mundo');}
.
After this first point, callbacks is probably a topic you will want to delve into, and that will be much of the confusion. The reason you receive a callback is because the function is asynchronous and will only be called later when an HTTP request is made.
I would like to make a small counterexample of your area function with callbacks , but not without first correcting:
function area(a, b) {
let c = a * b;
return c;
}
This same function could be written with a callback even though it did not make much sense because it is not asynchronous. But it would look like this:
function area(a, b, callback){
let c = a * b;
callback(c);
};
area(10, 5, function(resultado) {
console.log(resultado);
});
In this example the callback is a function that receives the result and does anything with it, and would make sense if it were asynchronous.
Let's then modify this example by including a setTimeout
:
function area(a, b, callback){
let c = a * b;
setTimeout(() => callback(c), 2000); //só processa o resultado passado 2 segundos
};
area(10, 5, function(resultado) {
console.log(resultado);
});
console.log("Calculo leva 2 segundos a ser feito");
Note that in both examples there is no return
because the function is asynchronous.
Returning now to Node and Express , function(req, res){
is actually callback , ie the function with the code you want to execute when that route is called. This can be called by several methods, such as get
, post
, patch
, delete
, among others and this is coded as string
in the first parameter. The callback is called with two parameters that are objects and usually take the name of req
and res
respectively, although they can have any other name you want.
The REQ parameter is in fact a client request
The req
parameter is an object with several of the request information that the client made, such as:
-
body
- contains key pairs value of request body
-
params
- contains the request parameters that are the dynamic part of the address
-
ip
- the ip address from which the request was started
And res
is also an object that represents the response and has several methods to control it, such as:
-
status
- change response http code
-
send
- send the response with its body
-
redirect
- to redirect to another route
I also advise you to take a look and explore Express documentation to get more into what these objects represent and all supported features