尝试在POST请求上发出消息,收到错误消息,指出无法读取未定义的属性emit
app.post('/webhook/orders/updated', function(req, res, next) {
io.socket.emit('order', "Order Id " + req.body.data.id + " : Updated");
});
在index.js中,我有以下代码:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
在用户界面上,我有以下代码:
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io();
socket.on('order', function(msg) {
$('#status').append($('<li class="alert alert-info">').text(msg));
});
});
</script>
答案 0 :(得分:1)
您必须选择要发出的套接字。
为此,我认为您需要在每个连接上将套接字ID传递给客户端,如下所示:
服务器端
var io = require('socket.io')(http);
io.on('connection', function (socket) {
socket.emit('connection:sid', socket.id);
});
客户端
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io();
socket.on('connection:sid', function(socketId) {
// Set socketId to your cookies, or global variable
});
});
</script>
然后,您必须将socketId发送到您执行的每个GET或POST请求,具有标头或参数。 最后,您可以在路线上访问正确的套接字:
<强> ROUTE 强>
app.post('/webhook/orders/updated', function(req, res, next) {
if (req.body.socketId) {
var socket = io.sockets.connected[req.body.socketId]; // Find socket by id
if (socket) {
socket.emit('order', "Order Id " + req.body.data.id + " : Updated");
}
else {
// No socket found with socketId
}
}
else {
// No socketId received
}
});
希望它有所帮助。
答案 1 :(得分:0)
替代解决方案。我将io.socket
替换为io.sockets
app.post('/webhook/orders/updated', function(req, res, next) {
io.sockets.emit('order', "Order Id " + req.body.data.id + " : Updated");
});