首页 > 解决方案 > 为什么我们在 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

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

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

标签: node.jsexpressnodejs-server

解决方案


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

const app = express();

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

var server = http.createServer(app); 

因为该app函数专门设计为一个 http 请求侦听器,它从传入的 http 请求传递参数,如您在 doc(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 库为您创建的函数。


推荐阅读