POST requests are sent twice with certain delay be

2019-07-08 09:47发布

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.

This is route:

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('/');
}

This is client side code:

$("#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;
    }
});

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.

Screenshot of terminal:

enter image description here

1条回答
倾城 Initia
2楼-- · 2019-07-08 10:08

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.

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

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

查看更多
登录 后发表回答