sayume
sayume

Reputation: 128

Json result with "undefined" prefixed

I use node https module to get auth information from another server, I get the result is "result=undefined{a:...,b:...}", so I can't use JSON.parse to parse the result data, but if I use "JSON.parse(body.substr(9))", I can get the right result. For more information, if I use a post tool to fetch the result, I get the result type is "application/json" and the result is the right json object. I use the following code to fetch post result.

 var options={
    hostname:...,
    port:null,
    path:...,
    method:'post',
    rejectUnauthorized:false,
    requestCert:true,
    agent:false
  }
  var https.request(options,function(res){
    var body;

    res.on('data',function(chunk){
       body+=chunk;
    });

    res.on('end',function(){
       console.log(JSON.parse(body));
    });
  });

Upvotes: 0

Views: 47

Answers (1)

go-oleg
go-oleg

Reputation: 19480

You should initialize body with an empty string:

var body = '';

because otherwise, the first time

body+=chunk;

is called, body is undefined and gets concatenated as the "undefined" string:

> var body;
undefined
> body += "{}"
'undefined{}'
> var body = '';
undefined
> body += "{}"
'{}'

Upvotes: 1

Related Questions