0

The previous answer requires the request component, of which I like to avoid using, due to academic purpose and other related policy. With vanilla Node.js 8.4.0, I tried:

var https = require('https');
var sendData = {
  api_key: 'abc',
  api_secret: '123',
  image_url: 'http://lalala.com/123/lalala.jpg',
  return_attributes: ['gender','age']
};
var options = {
  hostname: 'lalala.com',
  port: '443',
  path: '/info',
  method: 'POST',
  rejectUnauthorized: false,
  requestCert: true,
  headers: {
    'Content-Type': 'application/json',
  }
};
var openreq = https.request(options, function(serverFeedback){
  if (serverFeedback.statusCode == 200) {
    var body = '';
    serverFeedback.on('data', (data)=>{ body += data; })
      .on('end', ()=>{
        console.log(body);
      });
  } else {
    console.log('failed');
  }
});
openreq.write(JSON.stringify(sendData))
openreq.end();

Sadly the code above results in failed output.

Aero Wang
  • 8,382
  • 14
  • 63
  • 99

1 Answers1

1

There is nothing wrong with your request flow, as it almost exactly resembles Node.js documentation HTTP and HTTPS guides (apart from JSON Content-Type). However, you're only looking for 200 response and not expecting that error could have message in body that should be captured before serverFeedback.statusCode == 200 condition:

serverFeedback.setEncoding('utf8');
serverFeedback.on('data', (chunk) => {
  console.log(`BODY: ${chunk}`);
});
serverFeedback.on('end', () => {
  console.log('No more data in response.');
});

In any case, problem is definitely with the remote host then, and you could also observe response information more closely with:

console.log(`STATUS: ${serverFeedback.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(serverFeedback.headers)}`);

Just one more thing, if you're using version 8, for the same academic purposes it's worth reconsidering utilization of var in favor of let & const, as well as fat arrow functions and Promises instead of callbacks.

Damaged Organic
  • 8,175
  • 6
  • 58
  • 84