So trying to follow this answer here for setting up Socket.io to work in express app with /wwww file and index.js as router. (Ref: Using socket.io in Express 4 and express-generator's /bin/www)
ISSUE: 1) I can connect to the socket out of router.post. however when I try to create a connection inside of router.post to pass results to the client from the server - I can't connect.
- I can't send async data via socket.io
Console
a user connected index outside routerrr
Index.js
module.exports = function(io) {
io.on('connection', function(socket){
console.log('a user connected index outside routerrr');
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', async (req, res) => {
// Assign first query
searchedT = req.body.searchTerm;
queries.push(req.body.searchTerm);
// Invoke the async iterator
console.log("start....");
const results = await queryIterator(queries, async function(result) {
console.log("--->" + await result);
// Trying to connect to socket and send async data!!!!
io.on('connection', function(socket) {
console.log('a user connected inside routerrr');
socket.on('sentiment result', async function(result){
io.emit('sentiment result', await result);
});
});
// res.send(await result);
});
// res.send(result);
});
return router;
}
script.js
var socket = io();
function sendForm() {
let form = $('#message-entry');
let query = form.serialize();
$.post('/', query, async function (data) {
const results = await data;
$(function () {
// var socket = io();
socket.on('sentiment result', function(result){
$('#sentimentScore').text(result.sentimentResults.sentiment.score);
});
});
});
}