Express: Post 请求处理程序不会停止调用函数

Express: Post Request handler doesn't stop calling a function

我的快递应用程序应该调用一个函数一次,但它在处理POST请求时重复调用了无数次。我不明白为什么它被调用了不止一次。

此应用程序与 Slack 事件 API 配合使用,并在将消息 post 发送到特定 Slack 频道时从 Slack 接收事件作为 post 请求。一旦应用程序收到事件,它会以 200 状态响应来响应,以提醒 Slack 它收到了它。然后,应用程序从请求中提取文本 属性 并调用 postMessage 并将文本 post 消息发送到不同的频道。将消息发布到不同的频道不会启动另一个事件。

问题是 postMessage() 被无限调用,直到我手动使应用程序崩溃

我在这里设置应用程序并等待 post 请求:

const express = require('express');
var bodyParser = require('body-parser');

var app = express();
var jsonParser = bodyParser.json();

// Wait for post requests, then extract it's text
app.post('/', jsonParser, function (req, res) {
  if (!req.body){
    return res.sendStatus(400);
  } else {
    postMessage(req.body.event.text);     //Should be called once
  }

  // Respond to Slack Event API we received their request
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end();
  });
}

app.listen(config('PORT'), (err) => {
  if (err) throw err
  console.log(`App LIVES on PORT ${config('PORT')}`);
});

请求正文的结构如下:

body = {
  event: {
    text: "important message"
  }
}

不断被调用的函数。这将 post 一条消息发送到 Slack 频道:

function postMessage(message){
  var messagePath = 'https://slack.com/api/chat.postMessage?token=xxx&message=' + message;
  request(messagePath, function(error, response, body){
      if (!error && response.statusCode == 200){
          console.log('message sent successfully');
      } else {
          console.log('error == ' + error);
      }
  });
}

postMessage 方法确实使用正确的文本被调用。问题是它被调用了不止一次。

我认为 Slack 的 API 可能会多次发送相同的请求,但根据他们的文档,他们会在发送请求之间等待 3 秒。我的应用程序将在一秒钟内调用 postMessage() 大约一百次,所以我认为它不会因来自 Slack

的请求而超载

提前致谢!

我的猜测是您的机器人正在侦听发布的消息然后响应这些消息,它在发布时正在响应自己。这将导致无限循环。

解决方法是写一个检查以确保机器人没有响应自己。检查 req.body.event 并查看用户名是否随每条消息一起发送。然后你可以这样写:

app.post('/', jsonParser, function (req, res) {
    if (!req.body || !req.body.event){
        return res.sendStatus(400);
    } else if (req.body.event.user_name !== '<OUR_USER_NAME>') { // Make sure we are not responding to ourselves
        postMessage(req.body.event.text); // Should be called once
    }

    // Respond to Slack Event API we received their request
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end();
});