Curl with NodeJS

10,291

Solution 1

Simple example with request

var request = require('request');
request('http://www.httpbin.org', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
})

Example on how to use node-libcurl

var Curl = require('node-libcurl').Curl;
var curl = new Curl();
curl.setOpt( Curl.option.URL, 'http://www.httpbin.org');
curl.setOpt( Curl.option.FOLLOWLOCATION, true );
curl.setOpt( Curl.option.HTTPPOST, [
    { name: 'login', contents: 'username' }
]);
curl.perform();

Solution 2

Your server is not supported CURL. It will better if you use a request library https://github.com/request/request

var request = require('request');
var jsonData;

fs = require('fs')
fs.readFile('test.json', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  jsonData = JSON.parse(data);
});

request({
    url: 'https://mysite.atlassian.net/rest/api/2/issue/',
    'auth': {
     'user': 'userx',
     'pass': 'passx',
     'sendImmediately': false
    },
    qs: jsonData,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
});
Share:
10,291
Jobi
Author by

Jobi

Updated on June 29, 2022

Comments

  • Jobi
    Jobi almost 2 years

    I'm using the following code to execute a rest API using Curl with Node.JS. It is working on my local machine.

    ...
    ...
    var child_process = require('child_process');
    
        function runCmd(cmd)
        {
            var resp = child_process.execSync(cmd);
            var result = resp.toString('UTF8');
            return result;
        }
    
        var cmd = "curl -u userx:passx -X POST --data @test.json -H 'Content-Type: application/json' https://mysite.atlassian.net/rest/api/2/issue/";
        var result = runCmd(cmd);
    ...
    ...
    

    But after uploading to server, I'm getting the following error

    /home/ubuntu/PMPBuild/jiraIssue.js:76
                    var resp = child_process.execSync(cmd);
                                             ^
    TypeError: Object function (command /*, options, callback */) {
      var file, args, options, callback;