Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save euclid1990/dea53ab4cef8f018c3999c7c24f05126 to your computer and use it in GitHub Desktop.
Save euclid1990/dea53ab4cef8f018c3999c7c24f05126 to your computer and use it in GitHub Desktop.
PHP to Node.js: cURL with Basic Authentication
/*
<?php
// THE FOLLOWING IMPLEMENTATION CAN BE USED FOR VARIOUS APIs. THIS WAS TESTED SUCCESSFULLY ON THE pingdom.com API
$email = "your@mail.net";
$passwd = 'password';
$api_key = "API_KEY";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.domain.com/api/2.0/checks/");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_USERPWD, $email . ":" . $passwd );
curl_setopt($curl, CURLOPT_HTTPHEADER, array("API: " . $api_key ));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode( curl_exec( $curl ),true );
?>
*/
/****** NODE.JS ******/
var https = require("https");
var email = "your@mail.net";
var password = "password";
var api_key = "API_KEY";
https.request({
host: "api.domain.com",
path:"/api/2.0/checks/",
method: 'GET',
headers: {
"API": api_key,
"Authorization": "Basic " + new Buffer( email + ":" + password ).toString('base64')
}
}, function(res){
var response = "";
res.on('data', function(chunk){
response += chunk;
});
res.on('end',function(){
response = JSON.parse(response);
// DO STUFF WITH response HERE...
});
}).end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment