我正在重写代理服务器以使用mikeal的请求模块(使用流而不是缓冲区)并且遇到错误时未响应的响应问题。以下是代码的简化版本:
var request = require('request'),
connect = require('connect'),
port = 9090;
//get the api server id for proxy requests
var apiServer = process.argv[2];
apiUrl = 'https://'+apiServer+'.dev.myserver.com:'+port;
var app = connect();
app.use(connect.logger('dev'))
.use(function(req, res, next){
if( /^\/api\//.test(req.url) ){
var options = {
uri: apiUrl + req.url,
method: req.method,
body: req.rawBody,
headers: req.headers
};
req.pipe(request(options))
.on('error', function(err){
console.log( 'Error piping request object to mikeal/request(): ', err );
})
.pipe(res)
.on('error', function(err){
console.log( 'Error piping response from mikeal/request() to response object : ', err );
});
}
else {
next();
}
});
app.listen(port);
如果我向无法找到的API服务器发出请求,我会在控制台中登录以下内容并且请求会挂起(并最终超时,返回200):
将请求对象传递给mikeal / request()时出错:{[错误: getaddrinfo ENOTFOUND]代码:'ENOTFOUND',错误:'ENOTFOUND',系统调用: 'getaddrinfo'}
我应该在.on('error',...)处理程序中调用res.end()吗?如果是这样,我如何正确设置响应标题和正文?