I am able to emit a socket in my ExpressJS route file. But that emitted data is not read by the client side javascript.
server.js
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/node_modules'));
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('io', io);
var aws_router = require('./app/routes')(app);
server.listen(8080);
app/routes.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var path = require('path');
var process = require('process');
var aws_router = function(app, io){
app.get('/', function(req, res) {
//need to read from database
var socketio = req.app.get('io');
var objShopper = "hello"
console.log(objShopper)
socketio.emit("viewdata", objShopper);
res.sendFile(path.join(process.cwd() + '/index.html'));
});
return router;
}
module.exports = aws_router;
The socket emit portion works fine, at least I see no error and output hello in the console. But when I try to read the emitted data from client side JS, I can't read it.
client.js
$( document ).ready(function() {
var socket = io.connect('http://localhost:8080');
socket.on('viewdata', function (results) {
console.log("read data");
var objShopper = JSON.parse(results);
});
});
"read data"
is never shown in the console. What am I missing?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…