Search code examples
node.jsreactjsexpresspm2

Nodejs (express) running but requests not working


I run my project backend 'server.js' (express). it's working correctly and without any problem. But I send a request from Postman or another apps, I can not get any response or error. Only loading. Sometimes it works fine and I get all requests correctly but after few minutes or hours I cannot get any request responses. Please help me. What is cause this problem? I'am using Reactjs, Nodejs (express)


Solution

  • use this code as global error handling in your staring file. and you will get all error res as json.

    because chances are you might be having typo in your url. so with this code in place you will get .. not fount error res ... as json.

        
        // route not found
        app.use((req, res, next) => {
         const error = new Error('Not found');
         error.message = 'Invalid route';
         error.status = 404;
         next(error);
        });
       // log errors to console
        app.use(logErrors);
         //
        app.use(clientErrorHandler);
        app.use((error, req, res, next) => {
        res.status(error.status || 500);
          return res.json({
          status:error.status || 500,
          message: error.message,
          error: {
          error: error.message,
          },
        });
       });
    
    // log errors to console
    function logErrors(err, req, res, next) {
      console.error(err.stack);
      next(err);
    }
    // error handling for xhr request
    function clientErrorHandler(err, req, res, next) {
      if (req.xhr) {
        //console.log('xhr request');
        res.status(400).send({status: 400, message: "Bad request from client", error: err.message });
      } else {
        next(err);
      }
    }
    
    let port = process.env.PORT || 8081;
    app.listen(port, () => {
      console.log(`Listening on port ${port}`);
    });