gpt4 book ai didi

node.js - 我无法使用 socket.io 发送聊天消息

转载 作者:可可西里 更新时间:2023-11-01 11:13:10 25 4
gpt4 key购买 nike

我以前可以发送消息,但我按照本教程使用 redis 与 express 和 socket.io 共享了 passport 的 session http://www.scotthasbrouck.com/blog/2016/3/18/passportjs-express-session-with-sockeio现在我无法再发送任何聊天消息。

此外,在我的路由中,req.isAuthenticated() 总是返回 false,但我以前没有遇到过这个问题。

这是我的 server.js。

// server.js

// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var server = require('http').Server(app);

var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');


var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var passportSocketIo = require('passport.socketio');
var session = require('express-session');
var chatdb = require('./app/models/chat.js');
var user = require('./app/models/user.js');
var redis = require('redis');
var client = redis.createClient();
var RedisStore = require('connect-redis')(session);

// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

var sessionStore = new RedisStore({ host: 'localhost', port: 6379, client: client, ttl: 260 });

// required for passport
app.use(session({
secret: 'secret',
store: sessionStore,
resave: true,
saveUninitialized: true,
cookie: {
secure: process.env.ENVIRONMENT !== 'development' && process.env.ENVIRONMENT !== 'test',
maxAge: 2419200000
},

}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));
io.use(passportSocketIo.authorize({
key: 'connect.sid',
secret: 'secret',
store: sessionStore,
passport: passport,
cookieParser: cookieParser,
}));

var eventSocket = io.of('/chat');

// socket.io


io.on('connection', function (socket) {
console.log('a user connected');

socket.on('chat message', function(msg){
var name = "efe";
chatdb.saveMsg({name: name, msg: msg}, function(err){
if(err) throw err;
io.emit('chat message', msg);
});

if (socket.request.user && socket.request.user.logged_in) {
console.log(socket.request.user);
}
});


});

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
http.listen(port);
console.log('The magic happens on port ' + port);

最佳答案

我遇到了同样的问题。我尝试像您一样实现 passport.socketio,但没有它我解决了我的问题。

这是我的中间件:

// Express session middleware
var sessionMiddleware = session({ secret: 'secret-key', resave: true, saveUninitialized: true });

// Send Express sessionMiddleware through socket.io
io.use(function(socket, next){
// Params: request object, response object and callback.
sessionMiddleware(socket.request, {}, next);
});

sessionMiddleware 函数的第二个参数(响应对象)为空。这将使 session 呈现只读状态。

下面是我如何使用 passport js session 变量来获取用户信息:

io.on("connection", function(socket){
socket.on('chat message', function(msg){
var passport = socket.request.session.passport; // Get the passport variable

// Check if passport session exists
if (passport && typeof passport !== 'undefined'){

var userSession = passport.user; // Get the user session

// Build JSON with user session data
var message = {
message : msg,
name : userSession.name,
avatar : userSession.avatar
};

io.emit('chat message', message); // Emit my socket
}
});
});

希望对您有所帮助。

关于node.js - 我无法使用 socket.io 发送聊天消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com