简体   繁体   English

使用Express和Session在Node.js下用htpps配置socket.io

[英]Configure socket.io with htpps under Node.js with express and session

I passed few days ago my NodeJs app under https (thanks to let's encrypt ) 我几天前通过了https下的NodeJs应用程序(感谢我们加密

Problem is now socket.io won't connect anymore to my server. 现在的问题是socket.io将不再连接到我的服务器。 Here it's my front-end code (under React): 这是我的前端代码(在React下):

layout.jsx layout.jsx

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

Before the https socket.io was working just fine (I mean the code structure is ok.) Here it's my serverSide code: 在https socket.io正常工作之前(我的意思是代码结构还可以。)这是我的serverSide代码:

index.js: 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: 应用程序/ 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){
        ....

I'm not using store param becaused it's useless for me at this point. 我之所以不使用store参数,是因为这对我而言毫无用处。

And now the error in the browser: 现在浏览器中的错误:

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

SOLUTION FOUNDED 解决方案

While trying to write a good resume of my problem, I just founded the solution, and the problem. 在尝试写出我的问题的不错的履历时,我刚刚找到了解决方案和问题。 I just needed to pass the httpsServer into my socket and forget about the port: 我只需要将httpsServer传递到我的套接字中,而忽略端口:

app/socket.js: 应用程序/ 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;
};

And on the front side do not map any port: 并且在正面不映射任何端口:

layout.jsx layout.jsx

    //useless: socketHost: 'https://localhost',

    this.socket = io({secure: true});

So I don't have any question actually.. but I let this here if someone get stuck on the same kind of trouble. 所以我实际上没有任何问题。.但是,如果有人遇到同样的麻烦,我可以在这里提出。

Have a good day! 祝你有美好的一天!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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