2

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

{
    "name": "Test",
    "email": "[email protected]",
    "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": "[email protected]",
            "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?

2 Answers 2

7

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

   var request=require('request');

   var json = {
     "name": "Test",
     "email": "[email protected]",
     "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);
     }
   });
Sign up to request clarification or add additional context in comments.

6 Comments

Thank for reply. working but getting error : [Error: Invalid protocol: null]
there is some proxy issue
try to set your npm config proxy
Yes some API returns 200, 201 for success result
|
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
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.