HTTP和HTTPS同时(Express.Io)

时间:2014-11-05 16:34:41

标签: node.js http express socket.io express.io

我已成功收听端口443并可通过 https 访问服务器,但我无法使用 http 访问它。

var fs = require('fs')
options = {
    ca : fs.readFileSync('./ssl/site.com.pem'),
    key: fs.readFileSync('./ssl/site.com.key'),
    cert: fs.readFileSync('./ssl/site_com.crt')
}

var app = require('express.io')
app.https(options).io()
....
app.listen(443);

我尝试过使用http和https模块:

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

但这次socket.io在浏览器中提供了404。我怎么解决这个问题?我需要使用Express.Iosocket连接,因为应用程序是基于它的。

2 个答案:

答案 0 :(得分:0)

您应该将http重定向到https

 var express = require('express'),
 app = express(),  
 httpapp = express();

  //........................

 var credentials = {key: privateKey, cert: certificate, ca: ca};
 var httpsServer = https.createServer(credentials, app);
 var httpServer = http.createServer(httpapp);


 httpsServer.listen(443);
 httpServer.listen(80); 


 httpapp.route('*').get(function(req,res){  
    res.redirect('https://yourdomain.com'+req.url)
 });

答案 1 :(得分:0)

几天前遇到同样的问题,这个GitHub问题有所帮助: https://github.com/techpines/express.io/issues/17#issuecomment-26191447

您的代码是正确的,只需要进行一些更改。下面的代码是您提供的剪辑的略微修改版本。

var fs = require('fs'),
    express = require('express.io');

options = {
    ca : fs.readFileSync('./ssl/site.com.pem'),
    key: fs.readFileSync('./ssl/site.com.key'),
    cert: fs.readFileSync('./ssl/site_com.crt')
};

var app = express();
app.https(options).io();
var httpServer = require('http').createServer(app);

// ...

app.listen(443);
express.io.listen(httpServer);
httpServer.listen(80, function() { }, function() { });