简体   繁体   中英

How to update ExpressJS server's response to POST request after a timeout

I'm coding up a server using Node.js and ExpressJS.

The problem is that there will be a situation when client will send a POST request telling server to make some external device move up or down.

I want the server to send a initial response to that POST request saying that the device is moving. When the device stops, it will send that information to the server. Then I would like to change the response's body so it says that the device has stopped.

Is that possible in context of one response to one POST request?

For now I have prepared some mocked code of what I would like to accomplish. The setTimeout function simulates the device movement. The end of the timeout 'simulates' the device stopping moving (ie it moved all the way up)

res.send("MOVING");
setTimeout(function () {
    if (req.body.direction === "UP") {
        res.send("OPENED");
    } else {
        res.send("CLOSED");
    }
}, 1000);

I know that res.send() does end the connection between server and the client. It is placed there only to visualise better what I want to accomplish. I think that there used to be res.write() in ExpressJS back in the day, but it's not mentioned in the docs anymore. I also found an npm package called express-mung , but I don't think I can parametrize it (depending on the req.body.direction value the second response's value will be different).

As far as I know, this is out of the scope of HTTP requests. There should only be one response.

For your requirement I suggest using websockets.

https://socket.io/ is one of the popular choices.

In simple terms, you will have a websocket server along with your expressJs server. And from the client side, you will use the socketIo client to emit an event. Upon receiving the event, the server will emit back the first event(MOVING) to the target socket connection. Then after the timeout, it will emit another event (OPENED or CLOSED)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM