superagent icon indicating copy to clipboard operation
superagent copied to clipboard

response body(res.body) is always undefined.

Open haocs opened this issue 10 years ago • 5 comments

version: 1.8.3 
platform: nodejs

I am trying to use super agent in my nodejs application and find an issue that 'res.body' in my response is always undefined. The content in response is in Json and I can see it in res.text. After some investigation I am able to spot the code which cases this issue:

// /lib/node/index
// line 883 to 886

parse(res, function(err, obj){ // Expects an argument
  if (err && !self._aborted) self.callback(err);
  res.body = obj;
}

// lib/node/parsers/text.js
module.exports = function(res, fn){
  res.text = '';
  res.setEncoding('utf8');
  res.on('data', function(chunk){ res.text += chunk; });
  res.on('end', fn); // No argument is given.
};

As the above indicates, parse function's callback expects one argument but nothing is given when it is called.

haocs avatar May 18 '16 22:05 haocs

The text parser sets only .text.

For custom parsers it's sort-of broken. The end callback doesn't wait for the parser to finish - #950, so you need .buffer(true).

kornelski avatar May 19 '16 11:05 kornelski

I'm seeing this too - with a basic post:

      request
        .post(url)
        .send(postData)
        .set({ authorization: "Bearer " + this._accessToken })
        .end(function(err, res) {
          if (err) {
            cb(err);
          } else {
            log("RESPONSE >>>>>>> %j", res);
            cb(null, res.body);
          }
        })

res.body is always missing, even though the response I want is in string form in res.text.

Am I missing some configuration? Surely a basic json request/response works out of the box?

Thanks in advance.

TobyEalden avatar Sep 09 '16 07:09 TobyEalden

res.body is populated depending on Content-Type header in the response. If the server is (mis)configured to send the response as e.g. text/plain, then the response won't be parsed as anything else.

kornelski avatar Sep 09 '16 12:09 kornelski

Should be documented, or perhaps as FAQ. Thanks @pornel now response.body is not null :+1:

lesterzone avatar Oct 17 '16 02:10 lesterzone

thanks, @pornel

jeremy-linchao avatar Oct 24 '16 08:10 jeremy-linchao