Search code examples
javascriptnode.jsreactjssocketshttp-status-codes

How to handle Error: socket hang up while waiting Node and React


enter image description hereI've been working on a NodeJS express route the accepts a get request, counts and analyzes about 15000+ data, so from my react app (Axios) when I hit the get URL, the processing and analyzing takes more than 4 to 5 min and the socket hangs up on about 2min what should I do to make my react app wait longer or get a response in any other way. Maybe an HTTP 202 has its way but I don't know how to do it, Any Help?


Solution

  • the wise choice is to use websocket or socket-io for such use cases.

    but you can also :

    use express timeout . to keep the connection alive between the client and the server: first, install :

    npm install connect-timeout
    

    after that change your server entry point(app.js) file.

    var express = require('express')
    var timeout = require('connect-timeout')
    
    // example of using this top-level; note the use of haltOnTimedout
    // after every middleware; it will stop the request flow on a timeout
    var app = express()
    app.use(timeout('400s'))
    
    app.use(haltOnTimedout)
    
    
    // Add your routes here, etc.
    
    function haltOnTimedout (req, res, next) {
      if (!req.timedout) next()
    }
    
    app.listen(3000)
    

    for more details : express official

    or if you don't want to install any third-party module :

    app.use(function(req, res, next){
       res.setTimeout(120000, function(){
          console.log('Request has timed out.');
             res.send(408);
          });
    
          next();
     });