Get Https Response

Getting the body of an https response

You are printing body variable before data got triggered.

Try like below.

var https = require('https');
var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){
//save the data in a variable
var body = '';

response.setEncoding('utf8');
response.on('data', function (chunk){
body += chunk;
});

response.on('end', function() {
console.log(body); // prints nothing!
console.log('No more data in response.');

});
});

Refer:

https://nodejs.org/api/https.html#https_https_get_options_callback

Best way to check status code of http response?

The status code is the status property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok flag) before calling json:

fetch('https://jsonplaceholder.typicode.com/todos/1').then((response)=>{
console.log(response.status); // Will show you the status
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
});

How to get response from https.request in node outside of function

You can wrap your https.request call in a promise like this:

const makeRequest = function(options) {
return new Promise(function(resolve, reject) {
const req = https.request(options, function(res) {
res.setEncoding("utf8")
res.on("error", reject)
res.on("data", function(body) {
console.log(`Body: ${body}`)
resolve(body.status)
})
})
}

Then later you can do:

makeRequest({/*options*/})
.then(function(statusTrue) {
if (statusTrue) {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: true }),
}
} else {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: false }),
}
}
})
.then(function(ret) {
console.log(ret)
})
.catch(function(err) {
/* handle error */
})

Get HTTPS response

Here is a example which works for me under Ruby 1.9.3

require "net/http"

uri = URI.parse("https://api.twitter.com/1/statuses/user_timeline.json")
args = {include_entities: 0, include_rts: 0, screen_name: 'johndoe', count: 2, trim_user: 1}
uri.query = URI.encode_www_form(args)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri.request_uri)

response = http.request(request)
response.body

How to get HTTPS response

try this...

Https Connection Android

Make a HTTPS request through PHP and get response

this might work, give it a shot.


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);

for more info, check
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/



Related Topics



Leave a reply



Submit