Node.js 当NodeJS中的请求对象发生错误时,如何发送回调

Node.js 当NodeJS中的请求对象发生错误时,如何发送回调,node.js,http,Node.js,Http,我有一种情况,即我使用 request.on('error', function (e) { console.log("error while sending request: " + e); }); 但是我不知道如何将这个错误发送到客户端,在客户端我必须显示错误。我只能使用res.send()发送响应对象上的错误感谢您的帮助。我没有使用express。若要将响应对象上的错误返回到浏览器。您可以使用如下代码: const http = require

我有一种情况,即我使用

request.on('error', function (e) {
            console.log("error while sending request: " + e);
          });

但是我不知道如何将这个错误发送到客户端,在客户端我必须显示错误。我只能使用
res.send()发送响应对象上的错误感谢您的帮助。我没有使用express。

若要将响应对象上的错误返回到浏览器。您可以使用如下代码:

const http = require('http');

let server = http.createServer(function(req, res) {
  res.statusCode = 403;
  res.statusMessage = 'Forbidden';
  res.write(JSON.stringify({message: 'something bad happens'}));
  res.end();
});

server.listen(3000, function() { console.log("Server Listening on http://localhost:3000/"); });

这种“在请求对象上捕获错误”是否发生在Node.js web服务器中?我检查了文档,但找不到请求对象的“错误”事件。@shaochuancs搜索http.request(options[,callback])#,您可以找到它或尝试搜索.on('error'),似乎您正在使用Node.js作为http客户端,而不是服务器。那么“将此错误发送到客户端”是什么意思?在客户端捕获错误。。。