为什么我们在 http.createServer(app) 中传递“app”

Ama*_*yaz 5 node.js express nodejs-server

为什么我们在 http.createServer(app) 中传递“app”,因为我们也可以传递

例如:

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


var server = http.createServer(app) //here we pass app
Run Code Online (Sandbox Code Playgroud)

在其他代码中,我们传递了一些不同的参数,例如

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

jfr*_*d00 16

在你的第一个例子中,我假设app代表一个 Express 实例,如下所示:

const app = express();
Run Code Online (Sandbox Code Playgroud)

如果是这样,那么app请求处理函数也具有属性。你可以这样传递:

var server = http.createServer(app); 
Run Code Online (Sandbox Code Playgroud)

因为该函数专门设计为一个 http 请求侦听器,它传递来自传入 http 请求的app参数,如您在 doc 中看到的那样(req, res)

或者,在 Express 中,您也可以执行以下操作:

const server = app.listen(80);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它将http.createServer(app)为您执行此操作,然后还调用server.listen(port)并返回新的服务器实例。


当你这样做时:

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

您只需创建自己的函数来处理传入的 http 请求,而不是使用 Express 库为您创建的函数。


joh*_*mon 5

引用 Express 文档:\nexpress() 返回的应用程序实际上是一个 JavaScript 函数,旨在作为回调传递到 Node\xe2\x80\x99s HTTP 服务器来处理请求。这使得您可以轻松地为应用程序的 HTTP 和 HTTPS 版本提供相同的代码库,因为应用程序不会继承这些版本(它只是一个回调):

\n
    var express = require(\'express\')\n    var https = require(\'https\')\n    var http = require(\'http\')\n    var app = express()\n\n    http.createServer(app).listen(80)\n    https.createServer(options, app).listen(443)\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n