Last active
February 7, 2022 23:08
-
-
Save kostasx/36dca061bea3086c7bf9 to your computer and use it in GitHub Desktop.
PHP to Node.js: cURL with Basic Authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
<?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