【问题标题】:How to return NodeJS HTTP Request errors without waiting for timeout?如何在不等待超时的情况下返回 NodeJS HTTP 请求错误?
【发布时间】: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 状态代码。如果我有一个响应对象(当然)我可以这样做,但是直到超时到期我才得到一个。

我知道我一定错过了一些简单的东西,但我不知道它是什么。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    您提到您正在使用express。只需调用res.send(500) 以使用错误代码结束请求(在本例中为500

    【讨论】:

    • 我不需要一个 Response 对象来调用 .send() 吗?
    • Express 在对您的路由处理程序的调用中提供它。
    • 是的,这就是我所缺少的。谢谢!
    猜你喜欢
    • 2017-07-30
    • 2020-01-16
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多