Making curl request with node-libcurl returns bad authentication error response

911 Views Asked by At

I'm trying to make a POST request to the checkr api using node-libcurl. I need to create and send background check invitation to candidates but I get a Bad authentication error response from their api. Any help?

server.js

const data = {
'candidate_id': 'someid',
'package': 'driver_pro',
};

var checkr_sk =  'my_secret_key';

const Curl = require( 'node-libcurl' ).Curl;
curl = new Curl();
curl.setOpt(Curl.option.URL, `https://api.checkr.com/v1/invitations/${checkr_sk}`);
curl.setOpt('FOLLOWLOCATION', true);
curl.setOpt(Curl.option.POST, true);
curl.setOpt(Curl.option.HTTPHEADER, ['Content-Type: application/json']);
curl.setOpt(Curl.option.POSTFIELDS, JSON.stringify(data));

curl.on('end', function (statusCode, body, headers) {

var result = JSON.parse(body);
console.info(statusCode);
console.info(headers);
console.info(body);
console.info(this.getInfo(Curl.info.TOTAL_TIME));

this.close();
});

curl.on('error', function (err, curlErrorCode) {
console.error(err);
console.error(curlErrorCode);

this.close();
});

curl.perform();
1

There are 1 best solutions below

0
On BEST ANSWER

I found that the best way to make curl requests is with node-fetch library. First install node-fetch using npm. A good resource is this curl converter. You can find their repo on Github.

curl with node-fetch

const btoa = require('btoa');
const fetch = require('node-fetch');

const data = {
'candidate_id': 'someid',
'package': 'driver_pro',
};

var checkr_sk =  'my_secret_key';
fetch('https://api.checkr.com/v1/invitations', {
method: 'POST',
headers: {
    'Authorization': 'Basic ' + btoa(checkr_sk+':'),
    'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response){ return response.json(); })
  .then(function(data) {
     const items = data;
       console.log(items)
  })