Reputation: 92
I'm new to JavaScript and am trying to teach myself using code posted online. I'm unsure of the way arguments are passed into various functions at various levels.
For instance, in the node.js "Hello World" example (reproduced below), where do the 'req' and 'res' variables come from and how does the client call the server and pass this information to it (and get the result) !?!
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Upvotes: 2
Views: 375
Reputation: 37691
It's just a function body that is passed to the createServer
method. The variables req
and res
don't exist as they are not variables, they are the function parameters, and those names are commonly used for readability, but in no way are obligatory - for example, the code would work the same if you did:
http.createServer(function (a, b) {
b.writeHead(200, {'Content-Type': 'text/plain'});
b.end('Hello World\n');
}).listen(1337, '127.0.0.1');
You know, just like when you define a function:
function someFunction(firstParam, secondParam) {
// do something with firstParam and secondParam
}
But I'm not sure how a function with no name (anonymous) nested inside another function (or method) is called from somewhere else.
See if this helps you understand:
function add(a,b){return a+b}
function sub(a,b){return a-b}
function math(f, x, y) {
alert(f(x, y));
}
math(add, 1, 2);
math(sub, 8, 4);
// pass in anon function - multiplication
math(function(a, b){return a * b}, 2, 5);
Upvotes: 2
Reputation: 2286
Have a look at the docs. They help: https://nodejs.org/api/http.html#http_http_createserver_requestlistener
http.createServer is creating an instance of http.Server. http.Server is an event emitter, which can emit several events, including "request."
The function you pass in as a parameter is the RequestListener. The function you are passing in is the requestListener which is bound to the "request" event.
So you are creating an instance of http.Server, which emits events and calls functions in response to those events. Suppose your instance of http.Server is http_server
Underneath the hood, http_server probably does something like:
http_server.on('request', [yourFunction])
Node implicitly sends req and res into your function. So every time a client makes a request to your server, it emits the "request" event. Then since [yourFunction] is bound to the request event, it gets called with the req and res parameters passed in.
Upvotes: 1
Reputation:
Req -> Http (https) Request Object. You can get the request query, params, body, headers and cookies from it. You can overwrite any value or add anything there. However, overwriting headers or cookies will not affect the output back to the browser.
Res -> Http (https) Response Object. The response back to the client browser. You can put new cookies value and that will write to the client browser (under cross domain rules) Once you res.send() or res.redirect() or res.render(), you cannot do it again, otherwise, there will be uncaught error.
req = {
_startTime : Date,
app : function(req,res){},
body : {},
client : Socket,
complete : Boolean,
connection : Socket,
cookies : {},
files : {},
headers : {},
httpVersion : String,
httpVersionMajor : Number,
httpVersionMinor : Number,
method : String, // e.g. GET POST PUT DELETE
next : function next(err){},
originalUrl : String, /* e.g. /erer?param1=23¶m2=45 */
params : [],
query : {},
readable : Boolean,
res : ServerResponse,
route : Route,
signedCookies : {},
socket : Socket,
url : String /*e.g. /erer?param1=23¶m2=45 */
}
res = {
app : function(req, res) {},
chunkedEncoding: Boolean,
connection : Socket,
finished : Boolean,
output : [],
outputEncodings: [],
req : IncomingMessage,
sendDate : Boolean,
shouldkeepAlive : Boolean,
socket : Socket,
useChunkedEncdoingByDefault : Boolean,
viewCallbacks : [],
writable : Boolean
}
Upvotes: 1