node.js - 将附加参数传递给 node.js 回调

标签 node.js

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

类似于下面的内容,但是构建代码以允许访问响应并以尽可能松散的耦合写回 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);

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

关于node.js - 将附加参数传递给 node.js 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113622/

相关文章:

javascript - else if 的多个条件的正确代码

node.js - 在 VS Code 中启用 Javascript 的隐式类型检查会导致 "Cannot find name ' require'"错误

c - 获取已运行进程的子进程ID

javascript - 使用 Node JS 将多个数组转换为对象到一个数组

node.js - 使用 Node.js 测试 ElasticSearch填充 MongoDB 后强制更新索引

php - 如何在端口而不是 htdocs 文件夹中运行 PHP 应用程序?

javascript - 将文件从 Electron 发送到连接在 LAN 中的服务器

javascript - 使用 node-mysql 同时查询

node.js - Hapijs-react-views 设置

javascript - Mongoose "schema method"回调不工作