【发布时间】:2014-05-21 18:58:07
【问题描述】:
我有一个基于 NodeJS/Express 和 AngularJS 的应用程序,它通过 REST API 与应用程序服务器通信。如果应用程序服务器没有运行,我想立即向 AngularJS 客户端返回调用失败的错误。
这是我目前拥有的:
var jsonObject = JSON.stringify(input);
var postHeaders = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(jsonObject, 'utf8')
};
var options = {
host: '127.0.0.1',
port: 7777,
path: path,
method: method,
headers: postHeaders
};
var appServerRequest = http.request(options, function(appServerResult) {
console.log('STATUS: ' + appServerResult.statusCode);
console.log('HEADERS: ' + JSON.stringify(appServerResult.headers));
appServerResult.setEncoding('utf8');
var responseDataString = '';
appServerResult.on('data', function(chunk) {
responseDataString += chunk;
console.log('BODY: ' + chunk);
});
appServerResult.on('end', function() {
callback(responseDataString);
});
appServerResult.on('error', function(e) {
console.log('** Result ERROR in appServerResponse');
console.log(e);
});
});
appServerRequest.on('response', function(response) {
console.log('Response: ' + response);
});
appServerRequest.on('error', function(e) {
console.log('** Request ERROR in appServerRequest');
console.log(e);
});
appServerRequest.write(jsonObject);
appServerRequest.end();
如您所见,我正在监听 Request 和 Response 对象上的“错误”事件。当进行调用并且应用程序服务器未运行时,会按预期调用请求错误处理程序。但是,我无法弄清楚如何处理该错误并将其返回给客户端。最终会返回一个响应对象,但只有在超时到期之后。似乎应该有一种方法可以在我检测到错误后立即返回响应并指定适当的 HTTP 状态代码。如果我有一个响应对象(当然)我可以这样做,但是直到超时到期我才得到一个。
我知道我一定错过了一些简单的东西,但我不知道它是什么。
【问题讨论】: