【发布时间】:2019-04-13 18:52:28
【问题描述】:
期望的行为
我目前通过 jQuery.ajax() 请求更新 Node/Express/MongoDB 应用程序。
服务器响应被发送回 ajax 请求的成功处理程序,并在发送者的客户端上进行各种接口更改。
客户端
function update_database(parameters) {
$.ajax({
method: "POST",
url: "/api/v1/my_path",
data: parameters,
dataType: 'json',
cache: false,
headers: headers,
success: function(results) {
// perform interface changes
},
statusCode: {
500: function() {
console.log("that didn't work");
}
}
});
}
当然,这只是更新发送者的客户端。
我想更新所有连接的客户端。
我的尝试
official socket.io cheatsheet 显示相关方法是:
// send to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
在上下文中,official tutorial 的 Broadcasting 部分显示:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.broadcast.emit('hi');
});
问题
如何在路由处理程序的函数中socket.broadcast.emit?
我需要将每个broadcase.emit 包装在io.on('connection') 回调函数中吗?
以下内容不起作用,因为变量socket 尚未声明,但每次我想socket.broadcast.emit 时都必须使用io.on('connection') 包装器似乎“不正确”。
服务器端
// app setup
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// the route handler
app.route("/api/:api_version/my_path")
.post(api_my_post);
// the function
const api_my_post = (req, res) => {
// define the filter and update
var filter = { _id: o_id };
var update = { $set: { key: value } };
// perform the required database update
collection.findOneAndUpdate(filter, update, function(err, result) {
if (err) {
res.send(err);
} else {
// create an object to return
var response_json = { key: value, key_2: value_2 };
// return the object to the ajax success handler
res.json(response_json);
// return the object to all other connected clients
socket.broadcast.emit("ajax_response", response_json);
}
});
}
编辑:
以下答案看起来很有希望且相对简单,但似乎只适合io.emit 场景而不是socket.broadcast.emit 场景。
是否可以在路由中以某种方式访问socket 以允许使用socket.broadcast.emit?:
https://stackoverflow.com/a/31277123
基础配置:
var app = require('express')();
var server = app.listen(process.env.PORT || 3000);
var io = require('socket.io')(server);
// next line is the money
app.set('socketio', io);
内部路由或中间件:
exports.foo = function(req,res){
// now use socket.io in your routes file
var io = req.app.get('socketio');
io.emit('hi!');
}
【问题讨论】:
标签: jquery node.js mongodb express socket.io