Abhishek Kusnoor
Abhishek Kusnoor

Reputation: 308

Why is node js res.send not working?

I am using node in the backend and angular in the front end. I am checking whether a file exists in nodejs and sending the response to angular. This doesn't seem to be working. I am a beginner and I've searched extensively already before asking this here. Please pardon me for poor quality.

Node js code:

router.get('/api/checkstate', function(req, res) {
    //fs.readFileSync(req.query.resource, 'UTF-8');
      fs.stat('/Users/abhishek/message.txt', function(err, stat) {
    if(err == null) {
        res.send('Found');
    } else if(err.code == 'ENOENT') {
        res.send('Not found');
    } else {
        console.log('Some other error: ', err.code);
    }
  });
   //res.send('OK');
});

Angular code:

$scope.checkstate = function(){
        $http.get('/api/checkstate',function(data){
          if(data === 'Found'){
            $scope.button = "Unpause";
            console.log('Hello!!!');
          }
          else{
            $scope.button = "Pause";
          }
        });
      };

html:

<button ng-init="checkstate()" class="btn btn-primary toggle-btn" ng-click="togglefunc()" style="margin-top: -1200px;
  margin-left: 1000px;">{{button}}</button>

Upvotes: 0

Views: 7565

Answers (1)

James
James

Reputation: 82096

You only appear to be handling the response in specific error scenarios - you need to ensure you end the request for all scenarios otherwise the client will be waiting for a response indefinitely (or until the request eventually times out).

Also, given this is supposed to be an API, I would recommend you return the appropriate status code rather than a simple message

fs.stat('/Users/abhishek/message.txt', function(err, stat) {
    if (err && err.code === 'ENOENT') { 
        res.status = 404; // file does not exist
    } else if (err) { 
        console.log('Some other error: ', err.code);
        res.status = 500; // unknown error occurred
    } else { 
        res.status = 204; // file was found
    }
    res.end();
});

Then on the client you can leverage the success / error callbacks Angular provide rather than having to check the returned message.

$http.get('/api/checkstate').
    success(function(data, status, headers, config){
        $scope.button = "Unpause"; 
        console.log('File Found!');
    }).
    error(function(data, status, headers, config) {
        if (status === 404) {
            console.log('File Not Found!');
        } else {
            console.log('Other Error!');
        }
        $scope.button = "Pause";
    });

Upvotes: 1

Related Questions