'How does Node know that "req" and "res" are request and response objects in http.createServer(function(req, res))
I'm brand new to Node.js and I'm having a hard time understanding this. How does Node know that these two parameters are objects? Where do they come from? Are they provided by Node itself?
Solution 1:[1]
Whenever you use a library in Node.js, via something like require()
, you're actually importing all the code from that library, executing it, and generally getting a return value equal to that module's final module.exports
variable. So when you call a function from a library, that function was defined inside the library, including the definitions of how it decides to invoke any callbacks you pass to it. The names "req" and "res" can be anything -- you could call them "John" and "Amy" (but please don't, for clarity) -- but the first parameter will always be the request object and the second will always be the response object. Because that's the order the library passes them when it invokes your callback.
Most frameworks stick to the (req, res)
parameter structure simply because that's how the bundled HTTP library does it. They don't have to, but it's always nice when everyone is consistent, so you can easily guess how to use a new library :)
Solution 2:[2]
createServer()
is a function that expects one parameter - callback function. It takes that callback function that you provide (as anonymous function in our case), stores somewhere and calls it every time new request comes. Native code parses request to javascript object request
and passes it to your callback function alongside with object response
(which is a collection of callback functions for handling request). It is not node it is you the one who should know that node call you back with two arguments to make things happen.
Solution 3:[3]
Check the documentation:
https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener
https://www.w3schools.com/nodejs/nodejs_http.asp
https://www.w3schools.com/nodejs/met_http_createserver.asp
https://www.w3schools.com/nodejs/func_http_requestlistener.asp
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
Solution 4:[4]
I'm struggling with the same issue. I've read the docs too and the answers here as well. I'll give an answer but I'm not pretty sure about it.
First of all, I'll write the inheritance tree down (from different entries of the Node's Docs):
Class: EventEmitter
- Class: net.Server ---- Extends:
- Class: http.Server ---- Extends: <net.Server>
- http.createServer([options][, requestListener]) ---- Returns <http.Server>
- Class: http.Server ---- Extends: <net.Server>
- Class: net.Server ---- Extends:
Why http.createServer does have access to these two objects?. It does because of http.createServer returns a <http.Server> Class. This one has this "request" event that is
"Emitted each time there is a request."
and therefore, you have access to the request and response objects.But what does link the two events referenced before?. I guess that since http.createServer inherits from an EventEmitter class the "requestListener" is added to the list of "request" events similarly as it works EventEmitters when you add a new listener to a EventEmitter object (
"All EventEmitters emit the event 'newListener' when new listeners are added"
, further reading see below).If you read the request event's docs you'll see that has a request and response objects that belong to an <http.IncomingMessage> and a <http.ServerResponse> respectively. Then if you take a look at the docs of each one (see at the bottom of this comment) you'll know that once you create an http.server it'll pass the <http.IncomingMessage> as the first argument and <http.ServerResponse> as the second argument to the 'request' event.
From the Node's Docs:
Event: 'request'
- request <http.IncomingMessage>
- response <http.ServerResponse>
Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).
Class: EventEmitter
All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when existing listeners are removed.
- Event: 'newListener'
- eventName | The name of the event being listened for
- listener The event handler function
The EventEmitter instance willemit its own 'newListener' event before a listener is added to its internal array of listeners.
Listeners registered for the 'newListener' event are passed the event name and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the 'newListener' callback are inserted before the listener that is in the process of being added.
Class: http.IncomingMessage ---- Extends: <stream.Readable>
An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively.
It may be used to access response status, headers and data.
Class: http.ServerResponse ---- Extends: <http.OutgoingMessage>
This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | IceMetalPunk |
Solution 2 | mugiseyebrows |
Solution 3 | blfuentes |
Solution 4 |