0

I see code like below in almost every NodeJS application:

const express = require("express");
const app = express();

    app.post("/some-route", (req, res) => {
      const data = req.body;
    }

What I can not understand is where does the res come from? I can understand req comes from with the request that user/client application sends to the backend app, but what is this res object we should pass to the callback function almost always we want to write such a route handler function?

Isn't res what we should make in our handler function and send it back to the user? If so, how can we receive it as an input in our callback function?

Is this correct to say "Whenever the Express server receives a new request, it automatically creates a response object, and gives us the option to manipulate/modify this res object through the callback function? So we can either use this option and do something on that, then send it back to the client, or do nothing and express will send it's default or automatically created response back to the user"?

If so, what does a default express res object look like?

GoodMan
  • 542
  • 6
  • 19
  • 4
    The response object comes from the exact same place the request object does: Express passes it to your callback when handling an appropriate request. – jonrsharpe Sep 07 '22 at 18:31
  • 4
    This might help: https://expressjs.com/en/5x/api.html#res – Firmino Changani Sep 07 '22 at 18:32
  • This is Express code, and this is how the Express authors chose to make Express work. If you make your own HTTP library, you can set up your callbacks so that they must return a response object, rather than accepting one as an argument. Express chose to allocate an object for you and provide it to your callback, so that *every callback* wouldn't haven't have to contain the same boilerplate code to do so. – user229044 Sep 07 '22 at 18:40
  • What a default express response object looks like can be discerned best from the documentation that you've already been linked to. – user229044 Sep 07 '22 at 18:43

1 Answers1

1

Express just calls your function with the arguments

Check the example below:

const app = {
  post: (callback) => {
    callback('value1', 'value2')
  }
}

app.post((req, res) => {
  console.log(req, res)
})

app.post((first, second) => {
  console.log(first, second)
})

Here I create a custom post function which takes a function as a parameter. Then my post function calls the provided function with two arguments.

Take notice that these parameters can have arbitrary names, not only req and res

Konrad
  • 21,590
  • 4
  • 28
  • 64