Why we pass "app" in http.createServer(app)
Asked Answered
D

2

14

Why we pass "app" in http.createServer(app) as we can also pass

e.g :

var app = require('./app')
const http = require('http')
const port = 3500 || process.env.PORT


var server = http.createServer(app) //here we pass app

in other code we pass some different argument such as this

https.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
}).listen(port)
Divorcement answered 19/3, 2020 at 21:29 Comment(3)
These two cases are essentially the same: You pass a callback. I'd assume that the ./app module exports a callback. This is just like there is no difference between console.log(123) and var x = 123; console.log(x).Sulphuryl
@Sulphuryl I have my routes in app and app.use(),app.set,,,, ..... and we pass this all in http.createServer(app), this is no call backDivorcement
It is. Try console.log(typeof app), you will get 'function', and console.log(app.toString()), you will get 'function(req, res, next) {\n app.handle(req, res, next);\n }'. When you call Express' express(), you'll get a function that works as callback for the HTTP server and has a multitude of additional properties such as use, set, etc.Sulphuryl
P
18

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.

Playlet answered 20/3, 2020 at 3:28 Comment(0)
B
6

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

Bad answered 28/12, 2020 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.