I start by saying that app.get
is a normal function that takes two parameters: A path in the form of string
and a callback. Soon you can view this function so:
app.get(caminho, callback);
In your example the way is '/'
and the callback is function(req, res){res.send('Ola Mundo');}
.
After this first point, callbacks is probably a topic that you will want to delve into, and that will be a big part of the confusion. The reason you receive a callback is because the function is asynchronous and will only be called later when a request HTTP is made.
I take this opportunity 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 though it didn’t make much sense because it’s 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, the function(req, res){
is actually the callback, or the function with the code you want it to execute when that route is called. It can be called by several methods, such as get
, post
, patch
, delete
, among others and this is coded as string
in the first parameter. callback is called with two parameters that are objects and usually take the name of req
and res
respectively, although they may have any other name they want.
the actual REQ parameter is a client request
The parameter req
is an object with several of the order information the customer has made, such as:
body
- contains key order value pairs
params
- contains the order parameters that are the dynamic part of the address
ip
- the IP address from which the request originated
And the res
is also an object that represents the response and has several methods to control it, such as:
status
- change the response http code
send
- send the reply with its body
redirect
- to redirect to another route
I also advise to take a look and explore a little express documentation to stay more inside than represent these objects and all supported features
Very good, I passed there in a.b, I was typing without even thinking already, I will take a look at the documentation and the deeper concept of call back.
– David Ferrari