2

I have trying to send post call on https://api-mean.herokuapp.com/api/contacts with following data:

{
    "name": "Test",
    "email": "test@xxxx.in",
    "phone": "989898xxxx"
}

But not get any response. I have also tried it with postman it working fine. I have get response in postman.

I am using following nodejs code:

        var postData = querystring.stringify({
            "name": "Test",
            "email": "test@xxxx.in",
            "phone": "989898xxxx"
        });

        var options = {
            hostname: 'https://api-mean.herokuapp.com',
            path: '/api/contacts',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };

        var req = http.request(options, function (res) {
            var output = '';
            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', function () {
                var obj = JSON.parse(output.trim());
                console.log('working = ', obj);
                resolve(obj);
            });
        });

        req.on('error', function (e) {
            console.error(e);
        });

        req.write(postData);
        req.end();

Am I something missing?

How to send http post call from node server?

Mehul Mali
  • 3,084
  • 4
  • 14
  • 28

2 Answers2

7

I recommend you to use the request module to make things easier.

   var request=require('request');

   var json = {
     "name": "Test",
     "email": "test@xxxx.in",
     "phone": "989898xxxx"
   };

   var options = {
     url: 'https://api-mean.herokuapp.com/api/contacts',
     method: 'POST',
     headers: {
       'Content-Type': 'application/json'
     },
     json: json
   };

   request(options, function(err, res, body) {
     if (res && (res.statusCode === 200 || res.statusCode === 201)) {
       console.log(body);
     }
   });
abdulbarik
  • 6,101
  • 5
  • 38
  • 59
0

For sending HTTP-POST call from nodejs, you might need to use the request module

Sample:

var request = require('request');

request({
    url: "some site",
    method: "POST",
    headers: {
        // header info - in case of authentication enabled
    },
    json:{
        // body goes here
    }, function(err, res, body){
        if(!err){
            // do your thing
        }else{
            // handle error
        }
    });
iyerrama29
  • 496
  • 5
  • 15