发出的值不能添加到 DIV express.js socket.io
Emitted value cannot be added to DIV express.js socket.io
我有以下app.js
var express = require('express');
var app = express();
// var responseHandlerRouter = require('./routes/responseHandlerRouter.js');
routes = require('./routes');
var server = app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
io = require('/usr/local/lib/node_modules/socket.io').listen(server);
app.use('/', routes(io));
routes.js
var express = require('express');
var router = express.Router();
module.exports = function (io) {
// all of this router's configurations
router.get('/login', function (req, res, next) {
io.emit('notification', 'news');
res.end('well finally I am here');
});
return router;
}
index.html
<!doctype html>
<html>
<head>
<script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000/login');
socket.on('notification', function (data) {
console.log(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
当我在 URL 上执行 get 操作时,它应该发出但没有发生。它没有显示任何错误,但静静地失败了。
有什么问题吗?
更新
我想在 div 中显示 "news"。
但我无法按如下方式附加此内容
.... socket.on('notification', function (data) {
$('#messages').html(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>....
将使它有资格获得赏金
看来您使用路由器的方式有误。
不确定,但我认为 app.use('/login', routes(io))
而不是您所拥有的应该可以解决问题。
在您的实现中,您的路由器仅接收到 '/'
的 GET
编辑: 虽然接受了答案,但真正的解决方案在下面的评论中(错误的连接 url 指定)
我有以下app.js
var express = require('express');
var app = express();
// var responseHandlerRouter = require('./routes/responseHandlerRouter.js');
routes = require('./routes');
var server = app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
io = require('/usr/local/lib/node_modules/socket.io').listen(server);
app.use('/', routes(io));
routes.js
var express = require('express');
var router = express.Router();
module.exports = function (io) {
// all of this router's configurations
router.get('/login', function (req, res, next) {
io.emit('notification', 'news');
res.end('well finally I am here');
});
return router;
}
index.html
<!doctype html>
<html>
<head>
<script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000/login');
socket.on('notification', function (data) {
console.log(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
当我在 URL 上执行 get 操作时,它应该发出但没有发生。它没有显示任何错误,但静静地失败了。
有什么问题吗?
更新
我想在 div 中显示 "news"。 但我无法按如下方式附加此内容
.... socket.on('notification', function (data) {
$('#messages').html(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>....
将使它有资格获得赏金
看来您使用路由器的方式有误。
不确定,但我认为 app.use('/login', routes(io))
而不是您所拥有的应该可以解决问题。
在您的实现中,您的路由器仅接收到 '/'
编辑: 虽然接受了答案,但真正的解决方案在下面的评论中(错误的连接 url 指定)