How do I capture a “response end” event in node.js+express?

后端 未结 2 635
悲&欢浪女
悲&欢浪女 2021-02-11 14:12

I\'d like to write an express middleware function that sets up a listener on the response\'s \'end\' event, if one exists. The purpose is to do cleanup based on the http respon

相关标签:
2条回答
  • 2021-02-11 14:42

    Strangely enough, it appears that the response emits a "finish" event when the response is closed: http://sambro.is-super-awesome.com/2011/06/27/listening-for-end-of-response-with-nodeexpress-js/

    Despite this blog entry being a bit old, this event still exists (Line 836 in lib/http.js), so I assume it won't disappear soon, even though neither node's nor express' documentation mention it. By early 2014 it has moved to line 504 on of lib/_http_outgoing.js and still works.

    By the way, the "error" event on a server response is probably not something you'd usually want to see.

    0 讨论(0)
  • 2021-02-11 14:54

    Reading the documentation, here is the signature of res.send:

    res.send(body|status[, headers|status[, status]])
    

    Which means you can set your own status, like this: res.send( 'some string', 200 ); or even just res.send( 404 );.

    This method is the one you use to send the response.

    Once it is sent to the client, you can't access it anymore, so there is no callback.

    This is the last thing your server does. Once it has processed the request, it sends the response.

    However, you can access it before you send it to the client. Which means you can:

    console.log( res );
    res.send( datas );
    

    If you want to rollback/commit, you do it when the database's callback is called, not when the response is gone.

    0 讨论(0)
提交回复
热议问题