skip to Main Content

i am new to nodejs. referring to this link section http.createServer([options][, requestListener])
i know how to create the options object. but for the [, requestListener], it is stated in the docs that it is a <Function>. when i clicked on the link of <Function> which is here
it indicates that that <Function> is a normal function that could be lambda, however, in the docs of http.createServer([options][, requestListener]) as stated in the first link, it demonstrate the following:

http.createServer((req, res)

as far as i understood, the (req, res) is two different callbacks not a normal <Function>
to some extent. i am slightly befuddled.

1.would you please show me the difference between (req,res) and <Function>

2.where in docs (req,res) are explained. i want to know how can i configure or access properties of either of req and res

2

Answers


  1. You are misreading the code. (req, res) is not a parameter to createServer. This entire thing is an arrow function expression, a way to define an anonymous function:

    (req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    }
    

    It is largely (but not completely) equivalent to:

    function serverHandler(req, res) {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    }
    

    The differences (not really important here, but for completeness’ sake) are: the latter can be a function expression or a function statement, while the former is always an expression; the former does not redefine this while the latter does; and the former is not assigned to a variable, while the latter may be (serverHandler in this case).

    Given the latter definition of serverHandler, you could use it as follows:

    http.createServer(serverHandler)
    

    An anonymous arrow function expression is just doing the same job as a function identifier in this latter example.


    EDIT on where to find more documentation on req and res:

    Per documentation of createServer:

    The requestListener is a function which is automatically added to the 'request' event.

    Per documentation of 'request' event, the event callback gets two parameters: request, an instance of IncomingMessage, and response, an instance of ServerResponse.

    Login or Signup to reply.
  2. The req and res arguments to the callback are the same as the request and response properties of the corresponding request event.

    Event: ‘request’
    Added in: v0.1.0

    You can then follow the links to the documentation of those datatypes to see how you use them in your server.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search