node.js - NodeJS 请求 : How to get the response as a string?

标签 node.js express node-request

我有点迷路了。是否可以在 .on(response) 中将响应主体作为字符串获取(见下文)?还是我疯了?我知道我可以 .pipeWriteStream 的响应,但我需要将响应主体和响应 statusCode 放在同一位置才能继续我的代码。谢谢!

var request = require("request");
request(url)
.on('response', function(response) {
    console.log(response.statusCode); // 200
    console.log(/* I need to get response body string here */); // <--- can I have the response body as a string here?
})
.on("error", function(err){
    console.log("Problem reaching URL: ", err);
});

最佳答案

我想发表评论,但我不能。

就像在 npm 页面中一样(考虑到您不需要管道),您可以将正文与响应一起放在::

var request = require("request");

request(url, function (error, response, body) {
  console.log('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', body); 
}); 

关于node.js - NodeJS 请求 : How to get the response as a string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46396024/

相关文章:

node.js - 执行 https 请求时出现 CERT_UNTRUSTED 错误

node.js - 在 Node express 中再次调用相同的请求

javascript - 重构 NodeJs 函数

javascript - promise 所有 map 更新数组

c++ - 使用||在 Node.js 中

javascript - 将数据购物车存储到 cookie 中需要很大的空间

node.js - 如何使用 Sailsjs 创建 sitemap.xml

node.js - 从路由器发布响应中检索键值?

node.js - express 可以混合 html 和 jade 路由吗?

node.js - 如何从请求模块响应中存储cookie客户端