【问题标题】:How to send more responses after first response express app首次响应快递应用程序后如何发送更多响应
【发布时间】:2019-12-08 11:11:40
【问题描述】:

Facebook messenger api 要求在我的服务器上收到 webhook 请求后,在 20 秒内立即发送 200 响应。这可能比其余中间件完成执行所需的时间更长,因此我先发送 200 响应,然后开始执行中间件以处理在 messenger 上发送回复等。

但是,这会破坏 Jest,因为在从 jest 模拟函数检索到响应后,中间件会继续输出到控制台。我无法想到使用 res.send() 发送多个响应,因为它在内部调用 res.close()。

这是正确的方法吗?我不应该立即发送 200 响应吗?有没有办法发送多个?

我尝试过使用 res.write(),但它不会立即发送响应。

private webhookEndpoint = async (req: express.Request, res: express.Response): Promise<any> => {
        let body: MessageBodyRequest = req.body
        if (
            !isValidSHA1(
                process.env.APP_SECRET as string,
                JSON.stringify(req.body),
                req.get('X-Hub-Signature') as string
            )
        ) {
            console.error("Invalid webhook signature")
            return res.sendStatus(403);
        }

        // Checks this is an event from a page subscription
        if (body.object === 'page') {
            // Returns a '200 OK' response to all requests
            res.status(200).send('EVENT_RECEIVED')
            // Iterates over each entry - there may be multiple if batched
            try {
                //await triggers the try catch
                return await Promise.all(body.entry.map(async (entry) => {
                    let message = entry.messaging[0] //will only ever have 1 message
                    console.log("message received: ", message)
                    let messageReceived = new MessageReceived(message)
                    return messageReceived.handle() 
                }))
            } catch (error) {
                console.error("Error handling incoming message: ", error)
            }

        } else {
            // Returns a '404 Not Found' if event is not from a page subscription
            return res.sendStatus(404)
        }
    }

【问题讨论】:

  • 您也可以添加测试吗?另外,您的意思是因为继续执行而中断?因为如果那是行为,那么您也应该期望该控制台打印。
  • 一个 HTTP 请求可以有多个“响应”,但响应都有 1xx 范围内的状态码,例如 102 处理中。 stackoverflow.com/a/53231701/395461
  • 您的中间件在做什么,处理时间可能超过 20 秒?你能以某种方式减少它吗?
  • @Shannon 发送视频等事情需要很长时间才能等待

标签: node.js typescript express jestjs facebook-messenger-bot


【解决方案1】:

据我了解,除非发送 100 Continue 响应,否则无法为每个请求发送多个响应。请参阅W3 HTTP protocol documentation 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多