Mohamad3736
Mohamad3736

Reputation: 77

Callback functions parameters GET requests

Hi I am trying to understand how callback functions work and I have a question that will clear my doubts. when adding event listeners it is simple

$0.addEventListener("click", function(event){console.log(event)}); 

If i perform a "click" the following should happen.

But what about when there is two parameters in the callback function itself. Like in express. What does it mean?

app.get("/", function(req, res){
    res.sendFile(__dirname + "/page.html")
});

Why can't we just say

app.get("/", function(res){
    res.sendFile(__dirname + "/page.html")
});

one parameter in the event listener function worked but it does not work here. Why is that? What is the use of the "req", if we are already making a request in with the "/".

Upvotes: 0

Views: 960

Answers (3)

Ohad
Ohad

Reputation: 13

You can also use :

app.get("/", function({res}){
  res.sendFile(__dirname + "/page.html")
});

To understand why it works, you need to understand the implementation of Express API.

notice these three interfaces:

interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }
interface RequestHandler<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.RequestHandler<P, ResBody, ReqBody, ReqQuery> { }
interface RequestParamHandler extends core.RequestParamHandler { }

They define the req handler, and as you can see those interfaces generate an initialization values.

Then, when you don't use req it stills works from behind the scene.

So, why using app.get("/", function({res}) works? because then you keep the default values of req by not changing them and notice the compiler that there are few more callback parameters by putting {}.

I hope that explanation helped, pretty hard for me the explain that.

Upvotes: 0

Pavlo
Pavlo

Reputation: 44917

You can't skip an argument, because JavaScript refers to an argument by position:

app.get("/", function(
  res, // here you would be referring to request
  // actual response can be referenced here
){
  res.sendFile(__dirname + "/page.html")
});

If you don't need a reference to the first argument, the convention is to use an underscore for the name:

app.get("/", function(_, res){
  res.sendFile(__dirname + "/page.html")
});

Upvotes: 1

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

app.get("/", function(req, res){
    res.sendFile(__dirname + "/page.html")
});

The first parameter to the function is req and it can contain necessary information such as query string parameters used by the HTTP GET request by the user. The second parameter is used to send back the response to caller.

Since you are using the second parameter res, you can define the first parameter req and ignore it.

Upvotes: 0

Related Questions