POST请求被发送两次,它们之间有一定的延迟到Express路由 [英] POST requests are sent twice with certain delay between them to Express route

查看:279
本文介绍了POST请求被发送两次,它们之间有一定的延迟到Express路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条Express路线 / chat / send ,用于发送从会话和消息中获取用户ID的消息。它工作正常,但我注意到请求在一段时间后再次发送,没有任何操作(我在后台做了一些事情并再次检查了控制台)。我试图重新启动服务器并再次检查并且问题仍然存在。

I have an Express route /chat/send for sending messages which gets user's ID from session and message. It works okay, but I noticed that requests are sent again after some period of time, without any action (I was doing something in the background and checked console again). I tried to restart server and check again and problem persists.

这是路线:

app.post('/chat/send', ensureAuthenticated, (req, res) => {
    let id = req.user.id;
    let message = req.body.message;
    let currentTime = new Date().getTime();

    if (message.trim() !== "") {
        console.log('ID: ' + id + ' Message: ' + message + ' Time: ' + currentTime);
    }
});

// here is the method for ensuring that authentication is done

let ensureAuthenticated = (req, res, next) => {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/');
}

这是客户端代码:

$("#send-message").on("click", function() {
    $.post('/chat/send', { message: $("#chat-message").val() });
    $("#chat-message").val("");
});

$("#chat-message").keypress( function(e) {
    if (e.which == 13) {
        $.post('/chat/send', { message: $("#chat-message").val() });
        $("#chat-message").val("");
        return false;
    }
});

正如我所说,当发生这种情况时,我不在同一个标​​签中,所以我很确定我没有点击按钮发送消息或按Enter键。

As I said, I was not in the same tab when this happened so I'm pretty sure I haven't clicked on button for sending message or pressed Enter.

终端屏幕截图:

推荐答案

可以重试POST;因为您根本没有回复请求,所以没有响应传递给浏览器,并且它假定请求失败。 应该然后重试请求,这就是这里发生的事情。

POSTs can be retried; because you're not replying to the request at all, no response is ever delivered to the browser, and it assumes the request failed. It should then retry the request, which is what appears to be happening here.

要修复,只需回复Express处理程序中的任何内容,即使你只是打电话给 res.end()

To fix, just reply with anything in your Express handler, even if you just call res.end().

参考: https://tools.ietf.org/html/rfc2616#section-8.2.4

这篇关于POST请求被发送两次,它们之间有一定的延迟到Express路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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