简体   繁体   中英

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. I'm using resolveWithFullResponse set to true and have the json option set to true. I'm also using the gzip option if that makes a difference.

Is there anyway I can have request-promise automatically convert the response data to 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. 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;
            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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