Everything I have read so far explains that anonymous functions are created as so:
function (arg1, arg2) {
return arg1+arg2
}
And from the above arg1 and arg2 and can be any datatype depending on how I call it. This is all good and I understand that but this doesn’t seem to apply to certain Express functions or there is something I am not understanding correctly. On my first Express lesson here https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/start-a-working-express-server you use a callback function as so:
function(req, res) {
res.send('Response String');
}
This Express function looks identical to the function (syntax wise) I listed above but somehow it creates the res and req become objects (or they are reserved objects/words) because they have properties and methods like res.send.
The documentation for the Express app.METHOD says that it should be used as so:
app.METHOD(path, callback [, callback …])
so after “path” you specify a callback function. My understanding is that you create this function. They then give an example:
app.get('/user/:id', function (req, res) {
res.send('user ' + req.params.id)
})
here are my questions:
If we refer back to the very top of the post about my understanding of how functions work then it would imply that the ‘req’ argument somehow needs to be assigned a value when it is called. I am assuming that in this example the value is ‘/user/:id’ but how does it receive it? And how does this get passed through?
Also even if that was the case then the value of this ‘req’ varible/object would just be ‘/user/:id’ of the string datatype; but in the doco it clearly states that req and res are both objects with a bunch of properties. How does that work? Are these req and res objects somehow reserved words/variable/objects?
To show how all this conflicts, if we were to use the same app.get but replace their example callback function with mine above we would get:
app.get('/user/:id', function (arg1, arg2) {
console.log (arg1);
res.send('user ' + req.params.id)
})
In this last example it would log ‘/user/:id’ to the console. And as I understand it, it should just be a string so how is that then when arg1 and arg2 change to req and res do they somehow automatically become precanned objects with certain properties?