javascript - 在 Node.js 下使用express和session配置socket.io和htpps

标签 javascript node.js express https socket.io

几天前我在 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

最佳答案

找到解决方案

在尝试为我的问题写一份好的简历时,我刚刚找到了解决方案和问题。 我只需要将 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});

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

祝你有美好的一天!

关于javascript - 在 Node.js 下使用express和session配置socket.io和htpps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35239794/

相关文章:

JavaScript 的 confirm() 的 PHP 版本

javascript - 自动调整 Canvas 的所有可能尺寸

node.js - 如何重新翻译其他网站的图像(隐藏源 URL)

node.js - Number.isInteger 方法和 Node.js 版本

javascript - Sequelize 调用结构

javascript - 问题 : ng-repeat with specific view should be displayed on click

javascript - 我需要清除 JavaScript 中的 Set 来释放内存吗?

node.js - 运行 Jest 测试导致 'TypeError: Cannot read property ' Symbol(Symbol.toStringTag )' of undefined'

express - 如何将 ExpressJS 后端连接到 SvelteKit 前端?

javascript - Express 应用程序不听没有端口