Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created October 6, 2019 19:40
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/6eb8a6e77744927c854ce133c16cae67 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/6eb8a6e77744927c854ce133c16cae67 to your computer and use it in GitHub Desktop.
// Sending an HTTP Request from a NodeJS server
//const http = require("http");
const https = require("https");
const Stream = require("stream").Transform;
const fs = require("fs");
https
.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY", resp => {
let data = "";
// A chunk of data has been recieved.
resp.on("data", chunk => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on("end", () => {
let url = JSON.parse(data).hdurl;
console.log(url);
https.get(url, res => {
//the response should be an image
console.log(res.headers);
console.log(res.headers["content-type"], res.headers["content-length"]);
if (
res.statusCode == 200 &&
res.headers["content-type"] == "image/jpeg"
) {
let img = new Stream();
res.on("data", chunk => {
img.push(chunk);
});
res.on("end", () => {
let filename = __dirname + "/apod.jpg";
fs.writeFileSync(filename, img.read());
});
}
});
});
})
.on("error", err => {
console.log("Error: " + err.message);
});
/**
* Astronomy Picture of the Day (APOD)
* https://api.nasa.gov/planetary/apod?api_key=[Your API key here]
* PARAMS:
* api_key
* hd [Boolean] default false
* date [YYYY-MM-DD] default today
*
* RESPONSE:
* copyright
* date
* explanation
* title
* hdurl
* url
* media_type: 'image'
* service_version: 'v1'
*/
@obomheire
Copy link

Thank you, more power to you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment