死心塌地学网站

贴一 Node 和 express 的server

2018-10-23  本文已影响0人  落花流水__

原答案:

  1. Express.js - app.listen vs server.listen
  2. Difference between a server with http.createServer and a server using express in node js

陈述:

Express普遍写法

  var express = require('express');
  var app = express();
  //app.configure, app.use etc
  app.listen(1234);

app.listen 其实调用了node的HTTP包,不适用于 需要用HTTPS的环境
Express源码

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

在需要复用server时,express和node

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);
var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

总结:

app.listen 等于 http.createServer,但若需要https,还得用node的https.createServer

上一篇下一篇

猜你喜欢

热点阅读