套接字无法在 POST 内部发出 [英] Sockets fails to emit inside of POST

查看:35
本文介绍了套接字无法在 POST 内部发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

套接字无法在 POST 端点内发出.

Socket fails to emit inside of POST endpoint.

socket.emit("message", messageArr);

此 POST 不会发出任何套接字数据.我试图发送一些虚拟数据但它不起作用.但是当我在 POST 之外使用它时,数据没有问题.

This POST does not emits any socket data. I tried to send some dummy data and its not working. But when i use it outside of POST, the data comes in without problem.

我的想法是我需要每次 POST 进来时都向 FE 发送消息.因为它是 Twilio 的 Webhook(短信).

My idea is i need to Emit message to FE every time when POST comes in. Because its a Webhook for Twilio (sms).

 app.post("/twilio", (req, res) => {
        if (messageArr.number === req.body.To) {
          try {
            messageArr.body.push({ id: "client", text: req.body.Body });
          } finally {
            socket.emit("message", messageArr);
            console.log("Message Array", messageArr);
          }
        } else {
          messageArr = {
            number: req.body.To,
            body: [
              {
                id: "client",
                text: req.body.Body
              }
            ]
          };
          socket.emit("message", messageArr);
          console.log("Emit message array", messageArr);
        }

推荐答案

您的调用套接字在回调中,因此无法找到对它的内存引用,因此在 app.post 上方声明一个 var 并调用它,以便您可以访问如下图所示.

your calling socket inside a callback so it can't find the memory reference to it so declare a var above your app.post and call it so you can access it like shown below.

var _socket = socket;
app.post("/twilio", (req, res) => {
    if (messageArr.number === req.body.To) {
      try {
        messageArr.body.push({ id: "client", text: req.body.Body });
      } finally {
        _socket.emit("message", messageArr);
        console.log("Message Array", messageArr);
      }
    } else {
      messageArr = {
        number: req.body.To,
        body: [
          {
            id: "client",
            text: req.body.Body
          }
        ]
      };
      _socket.emit("message", messageArr);
      console.log("Emit message array", messageArr);
    }

这篇关于套接字无法在 POST 内部发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆