我在后端使用 Node ,在前端使用 Angular 。我正在检查 Nodejs 中是否存在文件并将响应发送到 Angular。这似乎不起作用。我是初学者,在在这里问这个问题之前我已经进行了广泛的搜索。质量不好请见谅。
Node 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');
});
Angular 代码:
$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>
最佳答案
您似乎只在特定错误场景中处理响应 - 您需要确保结束所有场景的请求,否则客户端将等待响应无限期地(或直到请求最终超时)。
此外,鉴于这应该是一个 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();
});
然后在客户端上,您可以利用 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";
});
关于javascript - 为什么 Node js res.send 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30597158/