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

为什么我们还要通过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

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

https.createServer(function (req,res) {
  res.writeHead(200,{'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
}).listen(port)
fan7286508 回答:为什么我们在http.createServer(app)中传递“ app”

在您的第一个示例中,我假设app代表类似这样的Express实例:

const app = express();

如果是,则app是一个请求处理程序函数,也具有属性。您可以这样传递它:

var server = http.createServer(app); 

因为app函数被专门设计为一个http请求侦听器,您可以从here in the doc看到传入的http请求向其传递参数(req,res)

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

const server = app.listen(80);

在这种情况下,它将为您执行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);

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

,

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

// obtain all the 'timerdisplay` elements
const pTimers = Array.from(document.querySelectorAll('.timerdisplay'));

...

// loop through each timer element
pTimers.forEach(p => {
  // set the time string here
});

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

本文链接:https://www.f2er.com/2615764.html

大家都在问