我创建了一个休息客户端来在我的应用程序之外进行调用。我想将从其余调用中收到的数据发送到客户端的网络浏览器。
类似于下面的内容,但是构建代码以允许访问响应并以尽可能松散的耦合写回 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();
})
}
最佳答案
使用request ,您可以将 API 响应直接传送到应用程序的响应。这样,它将是完全松散耦合的 — 您的服务器将准确返回 API 返回的内容。
request(options).pipe(res);
关于node.js - 将附加参数传递给 node.js 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113622/