S
S
squadbrodyaga2020-10-31 16:51:17
Node.js
squadbrodyaga, 2020-10-31 16:51:17

Duplicate messages in chat (Socket.io), what should I do?

Hello, I'm making a chat using socket.io. Solved some problems from previous questions,
but a new problem appeared.

  1. I start the server and write a message to the chat - everything is fine, the message is sent.
  2. I refresh the page and write the message again - 2 messages are sent at once.

And so on, how many times you refresh the page, the message is repeated so many times.

My code:
app.get('/index', async (req, res) => { 
    res.sendFile(path.join(__dirname, './HTML', 'index.html'))

    io.on('connection', socket => {
        socket.on('Отправить сообщение', (data) => {
            io.emit('Добавить сообщение', {
                msg: data,
                login: req.session.user.login
            })
        })
    })
})

Problem: As I understand it, the jamb is that with each GET request the socket is duplicated,
but I cannot write the Socket code not in the GET request, because then I will not have access to request ,
and I need it in order to send the login of the person who wrote the message.

  

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
squadbrodyaga, 2020-11-01
@squadbrodyaga

Solved a problem. It was necessary to create some kind of Middleware

const session = require('express-session')
const express = require('express')
const app = express()

const server = require('http').Server(app)
const io = require('socket.io')(server)

const sessionMiddleware = session({
    secret: '...',
    saveUninitialized: false,
    resave: false,
    store: ...
})

app.use(sessionMiddleware)
io.use((socket, next) => {
    sessionMiddleware(socket.request, {}, next)
})

io.on('connect', socket => {

    const session = socket.request.session
    
    // Используем примерно так:
    session.user.login
    
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question