在节点下使用 htpp 配置 socket.io.js使用 Express 和会话

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

本文关键字:js io 使用 Express 会话 socket 配置 节点 htpp      更新时间:2023-09-26

几天前我在https下通过了我的NodeJs应用程序(感谢让我们加密)

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

布局.jsx

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

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

索引.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);

应用/套接字.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

解决方案成立

在试图写一份关于我的问题的好简历时,我只是建立了解决方案和问题。我只需要将httpsServer传递到我的套接字中,而忘记端口:

应用/套接字.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;
};

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

布局.jsx

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

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

祝你今天开心!