Answer the question
In order to leave comments, you need to log in
How to send data through sockets?
Hello! How can I get data from an ExpressJS handler and "move" it into sockets?
The answer to the question "Why do this at all, if the data is already transmitted via response ?": Some of the data needs to be displayed in real time to all users on the page, and as far as I know, socket.io is designed just for this.
app.post('/test', jsonParser, (req, res) => {
const dto_test = {
test: 'asd'
}
const test = new Test(dto_test);
test.generateTest(result => {
// Здесь каким-то образом нужно передавать данные в сокет ниже.
res.json({
result: result.test
});
});
});
io.on('connection', (socket) => {
console.log('a user connected');
// Будущая отправка данных пользователю.
socket.on('disconnect', () => {
console.log('a user disconnected');
})
})
Answer the question
In order to leave comments, you need to log in
To send data to everyone, you need to call io.emit
test.generateTest(result => {
io.emit('some event', { result });
res.json({
result: result.test,
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question