node.js - 命中 Express 端点后在 socket.io 中发出

标签 node.js express socket.io

我是套接字新手

我正在与使用 socket.io 的客户端一起运行快速网络服务器。

基本上,每当有人点击我的一个发布请求时,我都会向我的客户发出一个结果,表明该发布请求已被点击。我想象它看起来像这样。

Node 服务器

const app = express();
app.post('/makeOrder', function(req, res){ 
   // Do some database logic that pushes the order into my database


   // This is where I'm stuck.
   // I want to notify the client that the order is placed.
   // Would it look something like this?
   io.in('kitchenSocket').emit('order-placed', 'An order has been placed!');


   // Last send something to finish the request
   res.send({test:"order placed"})
}

网络客户端

<script src="/socket.io.js"></script>
<script>
    // What I currently have
    var socket = io.connect('http://localhost:5554/kitchenSocket');
    socket.on('order-placed', function (data) {
        alert("an order has been placed:" + data)
    });
</script>

如何让它在被命中的快速端点上发出消息?

最佳答案

这是一些我必须做的事情非常相似的代码,您需要添加一些更改,但这是一个一般想法。主要区别是我使用的是 Redis 服务器。如果这有帮助或者您有后续问题,请告诉我。

服务器端代码

 var io = require('socket.io').listen(app);
      var redis = require('socket.io-redis');
      io.adapter(redis({ host: config.redis, port:config.redisPort }));
      //sets allowed origions
      io.set("origins", "*:*");
      let sockectObj = [data to be sent]
      io.emit('notification', sockectObj);

前端代码

this.socket = io(CONFIG.socket, { query: [naming parameter] });

this.socket.on("notification", function (resObj) {
  //Action to be performed
}.bind(this));

关于node.js - 命中 Express 端点后在 socket.io 中发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640406/

相关文章:

jquery-ui - YUI3 和 socket.io

javascript - 在 express 中使用套接字时出现问题

node.js - hummus 模块导致 npm 安装失败

node.js - 发送后无法设置标题

javascript - 文件上传 - Node Js(Express) 到 React Js。如何获取正确的图片路径?

mysql - 我需要帮助编写家谱的 MySQL INSERT 查询

node.js - 从套接字 io 访问 Express session

javascript - 如何告诉express js使用webpack+react作为前端

javascript - 在 promise 之外抛出错误

node.js - 引导 Alexa 做出特定槽值响应