简体   繁体   中英

Using both http-server and node express server

I've seen the following setup for a node express server:

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 is a request handler for an HTTP server. It needs an HTTP server in order to run. 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:

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 = 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.


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. 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. So, create one yourself if you need to create it with special options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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