Skip to content

Instantly share code, notes, and snippets.

@lanbau
Forked from kostasx/php2js-curl-basic-auth.js
Created August 27, 2018 09:38
Show Gist options
  • Save lanbau/46bd432b31f64766a1a9460cbc2e136f to your computer and use it in GitHub Desktop.
Save lanbau/46bd432b31f64766a1a9460cbc2e136f 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 = "[email protected]";
$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 = "[email protected]";
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