将其他参数传递给node.js回调

时间:2012-10-28 22:25:26

标签: node.js

我创建了一个rest客户端来在我的应用程序之外进行调用。我想将从其余调用收到的数据发送到客户端的Web浏览器。

如下所示,但是构造代码的最佳方法是什么,以允许访问响应以尽可能松散的耦合回写到Web浏览器?我不想在请求处理程序中定义其余客户端。

var servReq = http.request(options, function(restResponse){
    var status = restResponse.statusCode
    var headers = restResponse.headers
    restResponse.setEncoding("utf8");
    d='';
    restResponse.on('data', function(chunk){
        d += chunk;
    })
    restResponse.on('end', function(restResponse){
        // res would be a response to write back to the client's web browser
        // with the data received from the rest client.
        res.writeHead(200, {"content-type":"text/plain"})    
        res.write(d)
        res.end();
    })
}

1 个答案:

答案 0 :(得分:0)

使用request,您可以直接将API响应传递给应用程序的响应。通过这种方式,它将完全松散耦合 - 您的服务器将准确返回API返回的内容。

request(options).pipe(res);

https://github.com/mikeal/request#streaming