【问题标题】:Configure socket.io with htpps under Node.js with express and session在 Node.js 下用 express 和 session 配置 socket.io 和 htpps
【发布时间】:2016-02-06 10:12:30
【问题描述】:

几天前我通过了我在 https 下的 NodeJs 应用(感谢 let's encrypt

现在的问题是 socket.io 将不再连接到我的服务器。 这是我的前端代码(在 React 下):

layout.jsx

socketHost: 'https://localhost:9091',
...
this.socket = io(this.socketHost, {secure: true});
...
this.socket.on('update', function(data){ ...

在 https socket.io 工作正常之前(我的意思是代码结构还可以。) 这是我的服务器端代码:

index.js:

var app =  express();
app
.use(Session)
.use((req, res, next)=>{
    if(req.secure)
        next();
    else
        res.redirect('https://' + req.headers.host + req.url);
})
...
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(conf.mainPort);
httpsServer.listen(conf.httpsPort);

require('./app/socket')(httpsServer, Session, store);

app/socket.js:

...
io  = require('socket.io')(conf.socketPort),
ios = require('socket.io-express-session');
...
module.exports = function(app, session){

    var module = {};

    if(app && session){
        io.use(ios(session));
        io.on('connection', function(socket){
        ....

我没有使用store 参数,因为此时它对我来说毫无用处。

现在浏览器中的错误:

GET https://localhost:9091/socket.io/?EIO=3&transport=polling&t=1454751433013-95 
net::ERR_CONNECTION_REFUSED

【问题讨论】:

    标签: javascript node.js express https socket.io


    【解决方案1】:

    找到解决方案

    在尝试为我的问题写一份好的简历时,我刚刚找到了解决方案和问题。 我只需要将 httpsServer 传递到我的套接字并忘记端口:

    app/socket.js:

     io          = require('socket.io'),
     ios         = require('socket.io-express-session');
    
    var sockets  = {};
    
    module.exports = function(app, session){
    
        var module = {};
        if(app && session){
            io = io(app);
            io.use(ios(session));
        ...
    
        return module;
    };
    

    并且在前端不要映射任何端口:

    layout.jsx

        //useless: socketHost: 'https://localhost',
    
        this.socket = io({secure: true});
    

    所以我实际上没有任何问题.. 但是如果有人遇到同样的麻烦,我会在这里提出。

    祝你有美好的一天!

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 2017-04-10
      • 2014-10-20
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多