Why we pass "app" in http.createServer(app) Why we pass "app" in http.createServer(app) express express

Why we pass "app" in http.createServer(app)


In your first example, I'm assuming that app represents an Express instance from something like this:

const app = express();

If so, then app is a request handler function that also has properties. You can pass it like this:

var server = http.createServer(app); 

because that app function is specifically designed to be an http request listener which is passed the arguments (req, res) from an incoming http request as you can see here in the doc.

Or, in Express, you can also do:

const server = app.listen(80);

In that case, it will do the http.createServer(app) for you and then also call server.listen(port) and return the new server instance.


When you do this:

https.createServer(function (req, res) {  res.writeHead(200, {'Content-Type': 'text/plain'});  res.write('Hello World!');  res.end();}).listen(port);

you are just making your own function that's built to handle an incoming http request instead of using the one that the Express library makes for you.


Quoting the Express documentation:The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

    var express = require('express')    var https = require('https')    var http = require('http')    var app = express()    http.createServer(app).listen(80)    https.createServer(options, app).listen(443)

https://expressjs.com/en/api.html