简体   繁体   English

Nodejs-Request Promise从POST获取JSON响应主体

[英]Nodejs-Request promise get JSON response body from POST

I'm trying to make a POST request using request-promise to an HTTP service which returns back JSON data. 我正在尝试使用request-promise向HTTP服务request-promise POST请求,该服务将返回JSON数据。 I'm using resolveWithFullResponse set to true and have the json option set to true. 我正在使用resolveWithFullResponse设置为true,并将json选项设置为true。 I'm also using the gzip option if that makes a difference. 如果这gzip我也会使用gzip选项。

Is there anyway I can have request-promise automatically convert the response data to JSON? 无论如何,我可以让request-promise自动将响应数据转换为JSON吗? Currently, the response body is a string. 当前,响应主体为字符串。 Here is what my request options look like: 这是我的请求选项:

{
   url: 'http://foo.com/getData',
   json: true,
   body: {
      hello: world
   },
   resolveWithFullResponse: true,
   gzip: true
}

You should use transform option of the request module. 您应该使用请求模块的transform选项。 Find below the request object. 在请求对象下面找到。

{
   url: 'http://foo.com/getData',
   json: true,
   body: {
      hello: world
   },
   resolveWithFullResponse: true,
   gzip: true,
   transform: function (body, response) {
                if (response.headers['content-type'] === 'application/json') {
                    response.body = JSON.parse(body);
                }
                return response;
            }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM