What are the advantages of using http with express

2019-06-14 09:13发布

I've been using the Node.js express module for some time now, without ever using the http module to listen to the port.

I'm wondering what are the benefits of using:

app = express();
app.listen(app.get('port'));

over

app = express();
var server = http.createServer(app).listen(app.get('port'));

My guess is that it's something to do with being able to set http settings such as maxSockets etc, but is there any other reason people do this?

2条回答
太酷不给撩
2楼-- · 2019-06-14 09:32

express is a layer on top of connect which is a layer on top of http.

HTTP Interface API http

The http API Comes from Node. Only provides the basic HTTP functionality out the box.

  • networking
  • request, response
  • events
  • listening

Middleware Layer connect

Connect is a middleware framework for node, which allows you to write modular HTTP apps. It provides a bunch of middleware out of the box

  • middleware
  • static middleware
  • bodyParser
  • cookieParser
  • compress
  • csrf

Web Application Framework express

Express provides an additional layer on top of connect, which allows you to do even more stuff, and actually build real applications with it. Most notably, it provides you with routing.

  • routing
  • template engine support
  • configuration
  • file upload abstraction
查看更多
何必那么认真
3楼-- · 2019-06-14 09:53

From http://expressjs.com/api.html#app.listen:

The app.listen() method is simply a convenience method.

Here's the listen definition:

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

Notice it passes its arguments to the server's listen call, so you can still sett http settings like maxSockets.

It also says, "if you wish to use HTTPS or provide both, use the technique above." The technique above it refers to is:

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

So it seems one of the most common reasons not to use app.listen is if you want to have an https server.

I suppose you might need a reference to the return value of http.createServer for some reason, in which case you wouldn't want to use app.listen.

查看更多
登录 后发表回答