This code sends a GET request to the NASA API and displays the URL of the astronomical image of the day and its explanation in the console: JavaScript Copy the code const https = require('https'); https.get( api_key=DEMO_KEY', (resp) => { let data = ''; // Un morceau de réponse est reçu resp.on('data', (chunk) => { data += chunk; }); // La réponse complète à été reçue. On affiche le résultat. resp.on('end', () => { console.log(JSON.parse(data).explanation); }); }).on("error", (err) => { console.log("Error: " + err.message); }); Most of the functionality in the HTTP and HTTPS modules is rather low-level.
We receive the response in chunks rather than simply providing telegram philippines girl a callback function to be executed as soon as all the data is received. We also need to parse the response data manually. This is quite simple if it is formatted in JSON like here, but it is still an extra step. Since async/await is not available for HTTP requests made with this library, one approach to deal with this issue could be to use asynchronous streams . Although for somewhat complex cases it will take extra effort to read all the data, HTTP is a good solution if you want to avoid adding dependencies to your code or if you need low-level features.
Got Got is a great choice if you're looking for a lightweight library. It's designed to be easy to use and can also be used by default in Twilio Functions . Install Got with npm: Text Copy the code npm install [email protected] Because Got uses Promises, you'll find that it takes a lot less code to do the same thing as before, while still taking advantage of the async/await features: JavaScript Copy the code const got = require('got'); (async () => { try { const response = await got(' /apod?api_key=DEMO_KEY', { json: true }); console.
log(response.body.url); console.log(response.body.explanation); } catch (error) { console.log(error.response.body); } })(); This library does not parse JSON by default, that's why we had to add it { json : true }as a query argument. Got is a perfect option if you just want an easy to use and lightweight library. Axios Axios is another Promises-based HTTP client that works in both the browser and node.js. To install Axios with npm, enter the following command in your terminal: Text Copy the code npm install [email protected] The following code will display the URL and explanation of the astronomical photo of the day: JavaScript Copy the code const axios = require('axios'); (async () => { try { const response = await axios.
We receive the response in chunks
-
- Posts: 9
- Joined: Sun Dec 22, 2024 5:28 am