简体   繁体   English

同时使用http服务器和节点快速服务器

[英]Using both http-server and node express server

I've seen the following setup for a node express server: 我已经看到了节点快速服务器的以下设置:

server.js server.js

import { Server } from 'http'; 
import Express from 'express'; 

const app = new Express(); 
const server = new Server(app);

Since it is possible just to run express directly, what is the advantage here of returning the express server as an argument of the http server? 由于可以直接运行express,因此将express服务器作为http服务器的参数返回的好处是什么?

Express is a request handler for an HTTP server. Express是HTTP服务器的请求处理程序。 It needs an HTTP server in order to run. 它需要一个HTTP服务器才能运行。 You can either create one yourself and then pass app as the request handler for that or Express can create it's own HTTP server: 您可以自己创建一个,然后将app作为该请求处理程序传递给app程序,或者Express可以创建自己的HTTP服务器:

import Express from 'express'; 
const app = new Express();
app.listen(80);

But, just so you fully understand what's going on here. 但是,这样您就完全了解这里发生了什么。 If you use app.listen() , all it is doing is this (as shown from the Express code ): 如果您使用app.listen() ,那么它就是这样做的(如Express代码所示):

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

which is just creating its own vanilla http server and then calling .listen() on it. 这只是创建自己的.listen() http服务器,然后在其上调用.listen()


If you are just using a plain vanilla http server, then it saves you some code to have Express create it for you so there's really no benefit to creating it for yourself. 如果您仅使用普通的普通http服务器,那么它会为您节省一些代码来让Express为您创建它,因此为您自己创建它实际上没有任何好处。 If, you want to create a server with some special options or configurations or if you want to create an HTTPS server, then you must create one yourself and then configure it with the Express request handler since Express only creates a plain vanilla http server if you ask it to create it yourself. 如果要创建具有某些特殊选项或配置的服务器,或者要创建HTTPS服务器,则必须自己创建一个服务器,然后使用Express请求处理程序对其进行配置,因为Express仅在创建普通香草http服务器时才使用要求它自己创建。 So, create one yourself if you need to create it with special options. 因此,如果需要使用特殊选项进行创建,请自己创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM