为什么节点js res.send不起作用?

时间:2015-06-02 13:12:14

标签: javascript angularjs node.js express

我在后端使用节点,在前端使用角度。我正在检查nodejs中是否存在文件并将响应发送到angular。这似乎不起作用。我是初学者,在此问这里之前我已经进行了广泛的搜索。请原谅我的质量差。

节点js代码:

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');
});

角度代码:

$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>

1 个答案:

答案 0 :(得分:1)

您似乎只是处理特定错误情况中的响应 - 您需要确保终止所有方案的请求,否则客户端将等待响应无限期(或直到请求最终超时)。

另外,鉴于这应该是一个API,我建议你返回适当的状态代码而不是简单的消息

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();
});

然后在客户端上,您可以利用success / error回调Angular提供而不必检查返回的消息。

$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";
    });
相关问题