1

I am trying to do the following cUrl request in node.js using either request or http/https(or anything else if its not possible with those 2)

curl -k -3 -X POST https://somedomain.com/rest/ \
 -H "customeHeader: customeHeader" \  // customer header
 -d '{ "email" : "foo@bar.com", "password" : "yourpassword" }' // data to post.

this is what i got so far:

var options = {
        "hostname": "https://somedomain.com/rest/",
        "method": 'POST',
        "headers" : {
            "customeHeader" : "customeHeader"
        },
        "secureProtocol" : "SSLv3_method",
        "rejectUnauthorized" : false
    };

    var req = https.request(options, function(res) {
        res.on('data', function(d) {
            console.log(d);
            //process.stdout.write(d);
        });
    });
    req.end();

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

I think I'm only missing the Post fields(-d) or is the above completely wrong

Neta Meta
  • 4,001
  • 9
  • 42
  • 67
  • This stands out to me as a potential problem: `"hostname": "https://somedomain.com/rest/"`. The value you've given is not a hostname, it's a URL. `somedomain.com` is the hostname. The `http.request` method takes a `path` option that you should supply with the rest of the URL. Regardless, it would be helpful if you could tell us what errors you're getting, if any, or what behavior you're getting and how it differs from what you expect. – Jordan Running Mar 11 '14 at 20:52
  • Jordan thanks for the above tips i just figured those out, and yes the protocol / URI is not suppose to be supplied in the hostName, The only thing i am now missing is how/where to include the post fields – Neta Meta Mar 11 '14 at 20:55
  • 1
    I think you'll find the answers and comments on this post useful: http://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js – Jordan Running Mar 11 '14 at 21:26

1 Answers1

3

You need to write your POST body using req.write:

req.write(JSON.stringify(someObj));

Also set the Content-Type header to application/json.

Here’s a complete example:

var request = require('https').request,
    parseUrl = require('url').parse;

var options = parseUrl('https://somedomain.com/rest');
options.method = 'POST';
options.headers = {
  'Content-Type': 'application/json'
};

var req = request(options, function (res) {
  res.on('data', function (d) {
    console.log(d.toString());
  });
});

req.write(JSON.stringify({a: 1, b: 2}));

req.end();
Todd Yandell
  • 14,656
  • 2
  • 50
  • 37